Reading CLR via C # (15)-string with Xiaojing, familiar and unfamiliar

Source: Internet
Author: User

Not written for a long timeArticleNow, I picked up this book and learned to share it. It's a great pleasure. These two days I read the knowledge about writing strings.CodeAt the beginning, we basically had to deal with string every day, so we were no longer familiar with it. But take a closer look, there is still a feeling of getting rid of the cloud, and I understand some problems on weekdays.



I. String instantiation

1. Create a String object

String str1 = "Hello world."; // √

String str2 = new string ("Hello World"); // ×

Follow the error message to try the char [] type parameter and find the following:

String str2 = new string (New char [] {'h', 'E', 'l', 'l', 'O', '', 'w ', 'o', 'R', 'l', 'D'}); // √

2. Il code

String str1 = "Hello World"; the corresponding il code is:

We know that the Il code corresponding to the instantiation reference type is newobj, but we find that the string type is special andLdstr(Load string) command to build the object.

3. Notes:

    • String is directly inherited from system. object. It is a reference type and its instances are stored on the stack. In addition, string is a sealed class and cannot be inherited.
    • Line feed: envionment. newline is recommended for line feed instead of escape characters, because newline returns corresponding characters based on the platform, and can run normally across platforms in a timely manner.
    • @ Symbol: When a diagonal line appears in the file path or regular expression, you can add @ to the string to prevent false escape characters @. For example, @ "D: \ clrviac # \ demo01 ".
    • String and system. string: system. string is. A type defined in. NET Framework. string is a keyword defined in C #, representing system. string type, which can be considered as system. string. I have always considered it as a primitive type. It is not verified by the isprimitive method. (Thanks to fish Li for correcting ).
    • Tostring () method: The base class system. object contains this method. This class is generally redefined during use. If you are familiar with this method, I will not go into details.
Ii. String resident

1.One of the characteristics of a string is constant. Any operations on the string (such as substring and toupper) generate a new string, and the original string remains unchanged.

Let's take a look at an example to verify whether it is like this:

// ①
String str1 = "helloworld ";
String str2 = "helloworld ";
Console. writeline (referenceequals (str1, str2 ));
// ②
String str3 = "hello" + "world ";
Console. writeline (referenceequals (str1, str3 ));
// ③
String str4 = "hello ";
String str5 = "world ";
String str6 = str4 + str5;
Console. writeline (referenceequals (str1, str6 ));
// ④
Str6 = string. Intern (str6 );
Console. writeline (referenceequals (str1, str6 ));

The running result may differ from the previous prediction because CLR uses the string resident technology and creates a hash table. The key is a string, value is a reference to the string object in the managed heap. Whenever a new string instance is created, it first checks whether the same string already exists in the hash table.

Specific to the example above:

    • ① According to the string resident technology, the content of str1 and str2 strings is exactly the same and actually points to the same reference;
    • ② The string text constant str3 connected with + has completed the connection action during compilation, so str3 and str1 also point to the same reference;
    • ③ Str6 connects str4 and str5 at run time. In this process, multiple string objects are created. In the end, str6 and str1 point to different references.
    • ④ The string. Intern (string Str) method is called (described below) to force the use of the string resident technology, so str6 and str1 point to the same reference.

2. Two methods for accessing the hash table in the string type:

    • Public static string intern (string Str );

Obtain the hash code of a string object and check whether any matching item exists in the hash table. If yes, return the reference of the string object. If no, then, the copy is added to the hash table and the reference is returned.

    • Public static string isinterned (string Str );

Similar to the above method, the difference is that if no matching item exists, null is returned, and the string is not automatically added to the hash table.

3. Exercise caution when using resident services.

When there are a large number of string operations, the resident mechanism can indeed save memory, but we cannot abuse this mechanism. WriteProgramThis mechanism cannot always be used by default unless we explicitly call string. intern method to avoid unexpected errors, because this mechanism can be disabled by the compiler.. In addition, the string resident mechanism does not absolutely improve the performance and memory, because the string resident process also takes time. In short, you should be cautious when using it.

Iii. stringbuilder

Strings of the string type remain unchanged. A large amount of memory will be occupied when a large number of string operations such as string accumulation are performed. In this case, the system. Text. stringbuilder type is recommended.

1. Construct the stringbuilder object

Stringbuilder uses the New Keyword to construct an object, which is not as special as the string type. It has about 6 constructors, mainly used to allocate and initialize the status of the stringbuilder object, including:

    • Maximum string capacity. The default value is int32.maxvalue;
    • Character array: An array composed of char structures. It maintains the character content in the string;
    • Capacity: specify the length of the character array maintained by stringbuilder. The default value is 16. When the capacity is insufficient, it will automatically multiply.

2. Works with the string type

Stringbuilder can create corresponding string objects on the stack by using the tostring () method, which contains the string content in stringbuilder at this time. You can also use the append () method to add strings to stringbuilder again.

The methods provided by stringbuilder are not exactly the same as strings. They can be skillfully used to complete some string operations. Among them, tolower, trim, endswith and other methods are string, while replace and other methods are unique to stringbuilder.

For example:

Stringbuilder S = new stringbuilder ();
S. appendformat ("{0} {1}", "Cathy", "Chen"). Replace ("","-");
String S1 = S. tostring (). toupper ();
Console. writeline (S1 );

 

you may like it: Read CLR via C # (00) with Xiaojing-opening part and directory

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.