public ref class StringBuilder sealed public ref class StringBuilder sealed : System::Runtime::Serialization::ISerializable public sealed class StringBuilder public sealed class StringBuilder : System.Runtime.Serialization.ISerializable [System.Serializable] public sealed class StringBuilder [System.Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class StringBuilder : System.Runtime.Serialization.ISerializable type StringBuilder = class type StringBuilder = class interface ISerializable [<System.Serializable>] type StringBuilder = class [<System.Serializable>] [<System.Runtime.InteropServices.ComVisible(true)>] type StringBuilder = class interface ISerializable Public NotInheritable Class StringBuilder Public NotInheritable Class StringBuilder Implements ISerializable Inheritance Attributes SerializableAttribute ComVisibleAttribute Show
ISerializable The following example shows how to call many of the methods defined by the StringBuilder class. using namespace System; using namespace System::Text; int main() { // Create a StringBuilder that expects to hold 50 characters. // Initialize the StringBuilder with "ABC". StringBuilder^ sb = gcnew StringBuilder("ABC", 50); // Append three characters (D, E, and F) to the end of the // StringBuilder. sb->Append(gcnew array<Char>{'D', 'E', 'F'}); // Append a format string to the end of the StringBuilder. sb->AppendFormat("GHI{0}{1}", (Char)'J', (Char)'k'); // Display the number of characters in the StringBuilder // and its string. Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString()); // Insert a string at the beginning of the StringBuilder. sb->Insert(0, "Alphabet: "); // Replace all lowercase k's with uppercase K's. sb->Replace('k', 'K'); // Display the number of characters in the StringBuilder // and its string. Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString()); } // This code produces the following output. // // 11 chars: ABCDEFGHIJk // 21 chars: Alphabet: ABCDEFGHIJK using System; using System.Text; public sealed class App { static void Main() { // Create a StringBuilder that expects to hold 50 characters. // Initialize the StringBuilder with "ABC". StringBuilder sb = new StringBuilder("ABC", 50); // Append three characters (D, E, and F) to the end of the StringBuilder. sb.Append(new char[] { 'D', 'E', 'F' }); // Append a format string to the end of the StringBuilder. sb.AppendFormat("GHI{0}{1}", 'J', 'k'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); // Insert a string at the beginning of the StringBuilder. sb.Insert(0, "Alphabet: "); // Replace all lowercase k's with uppercase K's. sb.Replace('k', 'K'); // Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()); } } // This code produces the following output. // // 11 chars: ABCDEFGHIJk // 21 chars: Alphabet: ABCDEFGHIJK Imports System.Text Public Module App Public Sub Main() ' Create a StringBuilder that expects to hold 50 characters. ' Initialize the StringBuilder with "ABC". Dim sb As New StringBuilder("ABC", 50) ' Append three characters (D, E, and F) to the end of the StringBuilder. sb.Append(New Char() {"D"c, "E"c, "F"c}) ' Append a format string to the end of the StringBuilder. sb.AppendFormat("GHI{0}{1}", "J"c, "k"c) ' Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()) ' Insert a string at the beginning of the StringBuilder. sb.Insert(0, "Alphabet: ") ' Replace all lowercase k's with uppercase K's. sb.Replace("k", "K") ' Display the number of characters in the StringBuilder and its string. Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString()) End Sub End Module ' This code produces the following output. ' ' 11 chars: ABCDEFGHIJk ' 21 chars: Alphabet: ABCDEFGHIJKThis class represents a string-like object whose value is a mutable sequence of characters. In this section: The String and StringBuilder typesAlthough StringBuilder and String both represent sequences of characters, they are implemented differently. String is an immutable type. That is, each operation that appears to modify a String object actually creates a new string. For example, the call to the String.Concat method in the following C# example appears to change the value of a string variable named value. In fact, the Concat method returns a value object that has a different value and address from the value object that was passed to the method. Note that the example must be compiled using the /unsafe compiler option. using System; public class Example { public unsafe static void Main() { string value = "This is the first sentence" + "."; fixed (char* start = value) { value = String.Concat(value, "This is the second sentence. "); fixed (char* current = value) { Console.WriteLine(start == current); } } } } // The example displays the following output: // FalseFor routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exact a significant performance penalty. The alternative is to use StringBuilder, which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. A StringBuilder object maintains a buffer to accommodate expansions to the string. New data is appended to the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.
Important Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your code is executing, and the type of operation. You should be prepared to test your code to determine whether StringBuilder actually offers a significant performance improvement. Consider using the String class under these conditions:
Consider using the StringBuilder class under these conditions:
How StringBuilder worksThe StringBuilder.Length property indicates the number of characters the StringBuilder object currently contains. If you add characters to the StringBuilder object, its length increases until it equals the size of the StringBuilder.Capacity property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the StringBuilder object to exceed its current capacity, new memory is allocated, the value of the Capacity property is doubled, new characters are added to the StringBuilder object, and its Length property is adjusted. Additional memory for the StringBuilder object is allocated dynamically until it reaches the value defined by the StringBuilder.MaxCapacity property. When the maximum capacity is reached, no further memory can be allocated for the StringBuilder object, and trying to add characters or expand it beyond its maximum capacity throws either an ArgumentOutOfRangeException or an OutOfMemoryException exception. The following example illustrates how a StringBuilder object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a StringBuilder object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the StringBuilder object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the StringBuilder object 11 times. Whenever the append operation causes the length of the StringBuilder object to exceed its capacity, its existing capacity is doubled and the Append operation succeeds. using System; using System.Reflection; using System.Text; public class Example { public static void Main() { StringBuilder sb = new StringBuilder(); ShowSBInfo(sb); sb.Append("This is a sentence."); ShowSBInfo(sb); for (int ctr = 0; ctr <= 10; ctr++) { sb.Append("This is an additional sentence."); ShowSBInfo(sb); } } private static void ShowSBInfo(StringBuilder sb) { foreach (var prop in sb.GetType().GetProperties()) { if (prop.GetIndexParameters().Length == 0) Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)); } Console.WriteLine(); } } // The example displays the following output: // Capacity: 16 MaxCapacity: 2,147,483,647 Length: 0 // Capacity: 32 MaxCapacity: 2,147,483,647 Length: 19 // Capacity: 64 MaxCapacity: 2,147,483,647 Length: 50 // Capacity: 128 MaxCapacity: 2,147,483,647 Length: 81 // Capacity: 128 MaxCapacity: 2,147,483,647 Length: 112 // Capacity: 256 MaxCapacity: 2,147,483,647 Length: 143 // Capacity: 256 MaxCapacity: 2,147,483,647 Length: 174 // Capacity: 256 MaxCapacity: 2,147,483,647 Length: 205 // Capacity: 256 MaxCapacity: 2,147,483,647 Length: 236 // Capacity: 512 MaxCapacity: 2,147,483,647 Length: 267 // Capacity: 512 MaxCapacity: 2,147,483,647 Length: 298 // Capacity: 512 MaxCapacity: 2,147,483,647 Length: 329 // Capacity: 512 MaxCapacity: 2,147,483,647 Length: 360 Imports System.Reflection Imports System.Text Module Example Public Sub Main() Dim sb As New StringBuilder() ShowSBInfo(sb) sb.Append("This is a sentence.") ShowSbInfo(sb) For ctr As Integer = 0 To 10 sb.Append("This is an additional sentence.") ShowSbInfo(sb) Next End Sub Public Sub ShowSBInfo(sb As StringBuilder) For Each prop In sb.GetType().GetProperties If prop.GetIndexParameters().Length = 0 Then Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)) End If Next Console.WriteLine() End Sub End Module ' The example displays the following output: ' Capacity: 16 MaxCapacity: 2,147,483,647 Length: 0 ' Capacity: 32 MaxCapacity: 2,147,483,647 Length: 19 ' Capacity: 64 MaxCapacity: 2,147,483,647 Length: 50 ' Capacity: 128 MaxCapacity: 2,147,483,647 Length: 81 ' Capacity: 128 MaxCapacity: 2,147,483,647 Length: 112 ' Capacity: 256 MaxCapacity: 2,147,483,647 Length: 143 ' Capacity: 256 MaxCapacity: 2,147,483,647 Length: 174 ' Capacity: 256 MaxCapacity: 2,147,483,647 Length: 205 ' Capacity: 256 MaxCapacity: 2,147,483,647 Length: 236 ' Capacity: 512 MaxCapacity: 2,147,483,647 Length: 267 ' Capacity: 512 MaxCapacity: 2,147,483,647 Length: 298 ' Capacity: 512 MaxCapacity: 2,147,483,647 Length: 329 ' Capacity: 512 MaxCapacity: 2,147,483,647 Length: 360Memory allocationThe default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.MaxValue. These default values are used if you call the StringBuilder() and StringBuilder(String) constructors. You can explicitly define the initial capacity of a StringBuilder object in the following ways:
If the length of the string assigned to the StringBuilder object in the constructor call exceeds either the default capacity or the specified capacity, the Capacity property is set to the length of the string specified with the value parameter. You can explicitly define the maximum capacity of a StringBuilder object by calling the StringBuilder(Int32, Int32) constructor. You can't change the maximum capacity by assigning a new value to the MaxCapacity property, because it is read-only. As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a StringBuilder object doubles up to the value defined by the MaxCapacity property. In general, the default capacity and maximum capacity are adequate for most apps. You might consider setting these values under the following conditions:
Instantiating a StringBuilder objectYou instantiate a StringBuilder object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a StringBuilder object whose value is an empty string, but set its Capacity and MaxCapacity values differently. The remaining three constructors define a StringBuilder object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of Int32.MaxValue, whereas the third allows you to set the maximum capacity. The following example uses three of these constructor overloads to instantiate StringBuilder objects. using System; using System.Text; public class Example { public static void Main() { string value = "An ordinary string"; int index = value.IndexOf("An ") + 3; int capacity = 0xFFFF; // Instantiate a StringBuilder from a string. StringBuilder sb1 = new StringBuilder(value); ShowSBInfo(sb1); // Instantiate a StringBuilder from string and define a capacity. StringBuilder sb2 = new StringBuilder(value, capacity); ShowSBInfo(sb2); // Instantiate a StringBuilder from substring and define a capacity. StringBuilder sb3 = new StringBuilder(value, index, value.Length - index, capacity ); ShowSBInfo(sb3); } public static void ShowSBInfo(StringBuilder sb) { Console.WriteLine("\nValue: {0}", sb.ToString()); foreach (var prop in sb.GetType().GetProperties()) { if (prop.GetIndexParameters().Length == 0) Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)); } Console.WriteLine(); } } // The example displays the following output: // Value: An ordinary string // Capacity: 18 MaxCapacity: 2,147,483,647 Length: 18 // // Value: An ordinary string // Capacity: 65,535 MaxCapacity: 2,147,483,647 Length: 18 // // Value: ordinary string // Capacity: 65,535 MaxCapacity: 2,147,483,647 Length: 15 Imports System.Text Module Example Public Sub Main() Dim value As String = "An ordinary string" Dim index As Integer = value.IndexOf("An ") + 3 Dim capacity As Integer = &hFFFF ' Instantiate a StringBuilder from a string. Dim sb1 As New StringBuilder(value) ShowSBInfo(sb1) ' Instantiate a StringBuilder from string and define a capacity. Dim sb2 As New StringBuilder(value, capacity) ShowSBInfo(sb2) ' Instantiate a StringBuilder from substring and define a capacity. Dim sb3 As New StringBuilder(value, index, value.Length - index, capacity ) ShowSBInfo(sb3) End Sub Public Sub ShowSBInfo(sb As StringBuilder) Console.WriteLine() Console.WriteLine("Value: {0}", sb.ToString()) For Each prop In sb.GetType().GetProperties If prop.GetIndexParameters().Length = 0 Then Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)) End If Next Console.WriteLine() End Sub End Module ' The example displays the following output: ' Value: An ordinary string ' Capacity: 18 MaxCapacity: 2,147,483,647 Length: 18 ' ' Value: An ordinary string ' Capacity: 65,535 MaxCapacity: 2,147,483,647 Length: 18 ' ' Value: ordinary string ' Capacity: 65,535 MaxCapacity: 2,147,483,647 Length: 15Calling StringBuilder methodsMost of the methods that modify the string in a StringBuilder instance return a reference to that same instance. This enables you to call StringBuilder methods in two ways:
Performing StringBuilder operationsYou can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object. Iterating StringBuilder charactersYou can access the characters in a StringBuilder object by using the StringBuilder.Chars[] property. In C#, Chars[] is an indexer; in Visual Basic, it is the default property of the StringBuilder class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the Chars[] property. Characters in a StringBuilder object begin at index 0 (zero) and continue to index Length - 1. The following example illustrates the Chars[] property. It appends ten random numbers to a StringBuilder object, and then iterates each character. If the character's Unicode category is UnicodeCategory.DecimalDigitNumber, it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the StringBuilder object both before and after the values of individual characters were changed. using System; using System.Globalization; using System.Text; public class Example { public static void Main() { Random rnd = new Random(); StringBuilder sb = new StringBuilder(); // Generate 10 random numbers and store them in a StringBuilder. for (int ctr = 0; ctr <= 9; ctr++) sb.Append(rnd.Next().ToString("N5")); Console.WriteLine("The original string:"); Console.WriteLine(sb.ToString()); // Decrease each number by one. for (int ctr = 0; ctr < sb.Length; ctr++) { if (Char.GetUnicodeCategory(sb[ctr]) == UnicodeCategory.DecimalDigitNumber) { int number = (int) Char.GetNumericValue(sb[ctr]); number--; if (number < 0) number = 9; sb[ctr] = number.ToString()[0]; } } Console.WriteLine("\nThe new string:"); Console.WriteLine(sb.ToString()); } } // The example displays the following output: // The original string: // 1,457,531,530.00000940,522,609.000001,668,113,564.000001,998,992,883.000001,792,660,834.00 // 000101,203,251.000002,051,183,075.000002,066,000,067.000001,643,701,043.000001,702,382,508 // .00000 // // The new string: // 0,346,420,429.99999839,411,598.999990,557,002,453.999990,887,881,772.999990,681,559,723.99 // 999090,192,140.999991,940,072,964.999991,955,999,956.999990,532,690,932.999990,691,271,497 // .99999 Imports System.Globalization Imports System.Text Module Example Public Sub Main() Dim rnd As New Random() Dim sb As New StringBuilder() ' Generate 10 random numbers and store them in a StringBuilder. For ctr As Integer = 0 To 9 sb.Append(rnd.Next().ToString("N5")) Next Console.WriteLine("The original string:") Console.WriteLine(sb.ToString()) Console.WriteLine() ' Decrease each number by one. For ctr As Integer = 0 To sb.Length - 1 If Char.GetUnicodeCategory(sb(ctr)) = UnicodeCategory.DecimalDigitNumber Then Dim number As Integer = CType(Char.GetNumericValue(sb(ctr)), Integer) number -= 1 If number < 0 Then number = 9 sb(ctr) = number.ToString()(0) End If Next Console.WriteLine("The new string:") Console.WriteLine(sb.ToString()) End Sub End Module ' The example displays the following output: ' The original string: ' 1,457,531,530.00000940,522,609.000001,668,113,564.000001,998,992,883.000001,792,660,834.00 ' 000101,203,251.000002,051,183,075.000002,066,000,067.000001,643,701,043.000001,702,382,508 ' .00000 ' ' The new string: ' 0,346,420,429.99999839,411,598.999990,557,002,453.999990,887,881,772.999990,681,559,723.99 ' 999090,192,140.999991,940,072,964.999991,955,999,956.999990,532,690,932.999990,691,271,497 ' .99999Using character-based indexing with the Chars[] property can be extremely slow under the following conditions: Performance is severely impacted because each character access walks the entire linked list of chunks to find the correct buffer to index into.
Note Even for a large "chunky" StringBuilder object, using the Chars[] property for index-based access to one or a small number of characters has a negligible performance impact; typically, it is an 0(n) operation. The significant performance impact occurs when iterating the characters in the StringBuilder object, which is an O(n^2) operation. If you encounter performance issues when using character-based indexing with StringBuilder objects, you can use any of the following workarounds:
Adding text to a StringBuilder objectThe StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:
The following example uses the Append, AppendLine, AppendFormat, and Insert methods to expand the text of a StringBuilder object. using System; using System.Text; public class Example { public static void Main() { // Create a StringBuilder object with no text. StringBuilder sb = new StringBuilder(); // Append some text. sb.Append('*', 10).Append(" Adding Text to a StringBuilder Object ").Append('*', 10); sb.AppendLine("\n"); sb.AppendLine("Some code points and their corresponding characters:"); // Append some formatted text. for (int ctr = 50; ctr <= 60; ctr++) { sb.AppendFormat("{0,12:X4} {1,12}", ctr, Convert.ToChar(ctr)); sb.AppendLine(); } // Find the end of the introduction to the column. int pos = sb.ToString().IndexOf("characters:") + 11 + Environment.NewLine.Length; // Insert a column header. sb.Insert(pos, String.Format("{2}{0,12:X4} {1,12}{2}", "Code Unit", "Character", "\n")); // Convert the StringBuilder to a string and display it. Console.WriteLine(sb.ToString()); } } // The example displays the following output: // ********** Adding Text to a StringBuilder Object ********** // // Some code points and their corresponding characters: // // Code Unit Character // 0032 2 // 0033 3 // 0034 4 // 0035 5 // 0036 6 // 0037 7 // 0038 8 // 0039 9 // 003A : // 003B ; // 003C < Imports System.Text Module Example Public Sub Main() ' Create a StringBuilder object with no text. Dim sb As New StringBuilder() ' Append some text. sb.Append("*"c, 10).Append(" Adding Text to a StringBuilder Object ").Append("*"c, 10) sb.AppendLine() sb.AppendLine() sb.AppendLine("Some code points and their corresponding characters:") ' Append some formatted text. For ctr = 50 To 60 sb.AppendFormat("{0,12:X4} {1,12}", ctr, Convert.ToChar(ctr)) sb.AppendLine() Next ' Find the end of the introduction to the column. Dim pos As Integer = sb.ToString().IndexOf("characters:") + 11 + Environment.NewLine.Length ' Insert a column header. sb.Insert(pos, String.Format("{2}{0,12:X4} {1,12}{2}", "Code Unit", "Character", vbCrLf)) ' Convert the StringBuilder to a string and display it. Console.WriteLine(sb.ToString()) End Sub End Module ' The example displays the following output: ' ********** Adding Text to a StringBuilder Object ********** ' ' Some code points and their corresponding characters: ' ' Code Unit Character ' 0032 2 ' 0033 3 ' 0034 4 ' 0035 5 ' 0036 6 ' 0037 7 ' 0038 8 ' 0039 9 ' 003A : ' 003B ; ' 003C <Deleting text from a StringBuilder objectThe StringBuilder class includes methods that can reduce the size of the current StringBuilder instance. The Clear method removes all characters and sets the Length property to zero. The Remove method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a StringBuilder object by setting its Length property to a value that is less than the length of the current instance. The following example removes some of the text from a StringBuilder object, displays its resulting capacity, maximum capacity, and length property values, and then calls the Clear method to remove all the characters from the StringBuilder object. using System; using System.Text; public class Example { public static void Main() { StringBuilder sb = new StringBuilder("A StringBuilder object"); ShowSBInfo(sb); // Remove "object" from the text. string textToRemove = "object"; int pos = sb.ToString().IndexOf(textToRemove); if (pos >= 0) { sb.Remove(pos, textToRemove.Length); ShowSBInfo(sb); } // Clear the StringBuilder contents. sb.Clear(); ShowSBInfo(sb); } public static void ShowSBInfo(StringBuilder sb) { Console.WriteLine("\nValue: {0}", sb.ToString()); foreach (var prop in sb.GetType().GetProperties()) { if (prop.GetIndexParameters().Length == 0) Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)); } Console.WriteLine(); } } // The example displays the following output: // Value: A StringBuilder object // Capacity: 22 MaxCapacity: 2,147,483,647 Length: 22 // // Value: A StringBuilder // Capacity: 22 MaxCapacity: 2,147,483,647 Length: 16 // // Value: // Capacity: 22 MaxCapacity: 2,147,483,647 Length: 0 Imports System.Text Module Example Public Sub Main() Dim sb As New StringBuilder("A StringBuilder object") ShowSBInfo(sb) ' Remove "object" from the text. Dim textToRemove As String = "object" Dim pos As Integer = sb.ToString().IndexOf(textToRemove) If pos >= 0 sb.Remove(pos, textToRemove.Length) ShowSBInfo(sb) End If ' Clear the StringBuilder contents. sb.Clear() ShowSBInfo(sb) End Sub Public Sub ShowSBInfo(sb As StringBuilder) Console.WriteLine() Console.WriteLine("Value: {0}", sb.ToString()) For Each prop In sb.GetType().GetProperties If prop.GetIndexParameters().Length = 0 Then Console.Write("{0}: {1:N0} ", prop.Name, prop.GetValue(sb)) End If Next Console.WriteLine() End Sub End Module ' The example displays the following output: ' Value: A StringBuilder object ' Capacity: 22 MaxCapacity: 2,147,483,647 Length: 22 ' ' Value: A StringBuilder ' Capacity: 22 MaxCapacity: 2,147,483,647 Length: 16 ' ' Value: ' Capacity: 22 MaxCapacity: 2,147,483,647 Length: 0Modifying the text in a StringBuilder objectThe StringBuilder.Replace method replaces all occurrences of a character or a string in the entire StringBuilder object or in a particular character range. The following example uses the Replace method to replace all exclamation points (!) with question marks (?) in the StringBuilder object. using System; using System.Text; public class Example { public static void Main() { StringBuilder MyStringBuilder = new StringBuilder("Hello World!"); MyStringBuilder.Replace('!', '?'); Console.WriteLine(MyStringBuilder); } } // The example displays the following output: // Hello World? Imports System.Text Module Example Public Sub Main() Dim MyStringBuilder As New StringBuilder("Hello World!") MyStringBuilder.Replace("!"c, "?"c) Console.WriteLine(MyStringBuilder) End Sub End Module ' The example displays the following output: ' Hello World?Searching the text in a StringBuilder objectThe StringBuilder class does not include methods similar to the String.Contains, String.IndexOf, and String.StartsWith methods provided by the String class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a String value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows.
Let's examine these techniques in greater detail.
Converting the StringBuilder object to a stringYou must convert the StringBuilder object to a String object before you can pass the string represented by the StringBuilder object to a method that has a String parameter or display it in the user interface. You perform this conversion by calling the StringBuilder.ToString method. For an illustration, see the previous example, which calls the ToString method to convert a StringBuilder object to a string so that it can be passed to a regular expression method. Notes to CallersIn .NET Core and in the .NET Framework 4.0 and later versions, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. This can occur particularly when you call the Append(String) and AppendFormat(String, Object) methods to append small strings. ConstructorsProperties
Methods
Explicit Interface ImplementationsApplies to |