String is used to represent text. StringBuilder indicates an object similar to a String whose values are variable character sequences. It is variable because it is created after it is appended, removed, replaced, or inserted, you can also modify it. At the same time, it is more convenient to use StringBuilder when operating a string with a relatively large length.
The following is an example of the differences:
(1) different definitions
string str = “Hello World”;StringBuilder sb = new StringBuilder("Hello World");
(2) The display mode is different when the entire string is displayed.
Console.WriteLine("{0}",str);Console.WriteLine("{0}",sb.Tostring());
(3) different functions
Use string to display the nth element of a string, including the length of the string, spaces at the beginning and end of the string, copying, Case sensitivity, and string truncation.
Displays the nth element: str [n-1];
String length: str. length;
Remove the leading and trailing spaces of a string: str. Trim ();
Copy: str. Clone (). Tostring ();
Case: str. Toupper (); str. Tolower ();
Truncation: str. substring (n1, n2); // n1, n2 is the position of the first and last elements of the string in the original string.
StringBuilder is used to modify strings, such as adding texts and obtaining the maximum number of texts.
Add text at the end: sb. Append ("***"); // *** for the added content
Maximum number of retrieved texts: sb. MaxCapacity
Using System; using System. collections. generic; using System. text; namespace StringTypeCommon {class Program {static void Main (string [] args) {string str = "Hello World"; Console. writeLine ("show {0}", str); Console. writeLine ("first {0}", str [0]); Console. writeLine ("second {0}", str [1]); Console. writeLine ("insert character {0}", str. insert (6, "C #"); Console. writeLine ("String Length {0}", str. length); Console. writeLine ("delete string space {0}", s Tr. trim (); Console. writeLine ("string copy {0}", str. clone (). toString (); Console. writeLine ("lowercase string {0}", str. toLower (); Console. writeLine ("uppercase string {0}", str. toUpper (); Console. writeLine ("intercepting some strings {0}", str. substring (1, 6); StringBuilder sb = new StringBuilder ("Hello World"); Console. writeLine ("show {0}", sb. toString (); Console. writeLine ("End appended text {0}", sb. append ("!!! "); Console. writeLine ("Add text {0} at specified position", sb. insert (6, "dear"); Console. writeLine ("Maximum number of texts {0}", sb. maxCapacity); Console. readLine ();}}}