(Inherits from MfObject)
Represents a mutable string of characters. This class cannot be inherited.
Sealed Class
Properties, Methods, Related, Remarks, Example
Name |
Description |
|
Initializes a new instance of the StringBuilder class. |
||
Initializes a new instance of the StringBuilder class using the specified capacity. |
||
Initializes a new instance of the StringBuilder class that starts with a specified capacity and can grow to a specified maximum. |
||
Initializes a new instance of the StringBuilder class using the specified string. |
||
Initializes a new instance of the StringBuilder class using the specified string and capacity. |
||
Initializes a new instance of the StringBuilder class from the specified substring and capacity. |
Name |
Description |
|
Gets or sets the maximum number of characters that can be contained in the memory allocated by the current instance. |
||
Gets or sets the character at the specified character position in this instance. |
||
Gets the maximum capacity of the current StringBuilder object. |
||
Gets or sets the length of the current StringBuilder object. |
Name |
Description |
|
Appends the string representation of the Unicode characters in a specified list to this instance. |
||
Appends the string representation of a specified sublist of Unicode characters to this instance. |
||
Appends the string representation of a specified sublist of Unicode characters to this instance. |
||
Appends a copy of the specified string var or object to this instance. |
||
Appends a copy of the specified substring to this instance. |
||
Appends the string returned by processing a composite format string, which contains zero or more format items, to this instance. |
||
Removes all characters from the current StringBuilder instance. |
||
Compares this instance to a specified StringBuilder instance. Overrides MfObject.CompareTo() |
||
Copies the characters from a specified segment of this instance to a specified segment of a destination MfCharList. |
||
Ensures that the capacity of this instance of StringBuilder is at least the specified value. |
||
Returns a value indicating whether this instance is equal to a specified StringBuilder. Overrides MfObject.Equals() |
||
Gets A hash code for the current MfObject. Inherited from MfObject. |
||
Gets the Type for the for the Class .Inherited from MfObject. |
||
Inserts the string representation of the Unicode characters in a specified list to this instance. |
||
Inserts the string representation of a specified sublist of Unicode characters to this instance. |
||
Insert a copy of the specified string var or object to this instance. |
||
Inserts a specified number of copies of the string representation of a Unicode characters to this instance. |
||
Gets if current instance of StringBuilder is of the same type as ObjType or derived from ObjType. Overrides MfObject.Is() |
||
Get if the current class is an instance. Inherited from MfObject. |
||
Creates a shallow copy of the current MfObject instance. Inherited from MfObject. |
||
Removes the specified range of characters from this instance. |
||
Replaces, within a substring of this instance, all occurrences of a specified string with another specified string. |
||
Replaces, within a substring of this instance, all occurrences of a specified string with another specified string. |
||
Converts the value of this instance to a string var. Overrides MfObject.ToString() |
||
Converts the value of this instance to a string var or instance of MfString. |
||
Converts the value of this instance to a substring var or instance of MfString. |
||
Converts the value of this instance to a substring var or instance of MfString. |
This class repesents a string-like object whose value is a mutable sequence of characters.
In this section:
The String and StringBuilder types
Although StringBuilder and MfString both represent sequences of characters, they are implemented differently. MfString is an immutable type. That is, each operation that appears to modify a MfString object actually creates a new string.
For example, concat the following 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.
value := "This is the first sentence" . "."
Address1 := &Value
value := value . "This is the second sentence. "
value := value . "This is the third sentence. "
Address2 := &value
MsgBox % Address1 = Address2 ; displays 0 for false
For 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.
|
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 app is executing, and the type of operation. You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement. |
Consider using the MfString class under these conditions:
Consider using the StringBuilder class under these conditions:
The 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 MfArgumentOutOfRangeException or an MfOutOfMemoryException 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.
sb := new MfText.StringBuilder()
sb1 := new MfText.StringBuilder()
SbAppendInfo(sb1, sb)
sb1.Append("This is a sentence.")
SbAppendInfo(sb1, sb)
ctr = 0
While (ctr <= 10)
{
sb1.Append("This is an additional sentence.")
SbAppendInfo(sb1, sb)
ctr++
}
MsgBox % sb.ToString()
/*
Capacity: 16 MaxCapacity: 2147483647 Length: 0
Capacity: 32 MaxCapacity: 2147483647 Length: 19
Capacity: 64 MaxCapacity: 2147483647 Length: 50
Capacity: 128 MaxCapacity: 2147483647 Length: 81
Capacity: 128 MaxCapacity: 2147483647 Length: 112
Capacity: 256 MaxCapacity: 2147483647 Length: 143
Capacity: 256 MaxCapacity: 2147483647 Length: 174
Capacity: 256 MaxCapacity: 2147483647 Length: 205
Capacity: 256 MaxCapacity: 2147483647 Length: 236
Capacity: 512 MaxCapacity: 2147483647 Length: 267
Capacity: 512 MaxCapacity: 2147483647 Length: 298
Capacity: 512 MaxCapacity: 2147483647 Length: 329
Capacity: 512 MaxCapacity: 2147483647 Length: 360
*/
SbAppendInfo(sbIn, sbOut)
{
sbOut.AppendFormat("Capacity: {0:i} MaxCapacity: {1:i} Length: {2:i}", sbIn.Capacity, sbIn.MaxCapacity, sbIn.Length)
sbOut.AppendLine()
}
The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is MfIntInteger.MaxValue. These default values are used if you call the Constructor() and Constructor(value) 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 Constructor(capacity, maxCapacity) 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 object
You 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.
Constructor |
String value |
Capacity |
Maximum capacity |
Empty String |
16 |
||
Empty String |
Defined by the capacity parameter |
||
Empty String |
Defined by the capacity parameter |
Defined by the maxCapacity parameter |
|
Defined by the value parameter |
16 or value. Length, whichever is greater |
||
Defined by the value parameter |
Defined by the capacity parameter or value. Length, whichever is greater. |
||
Defined by value. Substring(startIndex, length) |
Defined by the capacity parameter or value. Length, whichever is greater. |
Defined by the maxCapacity parameter |
The following example uses three of these constructor overloads to instantiate StringBuilder objects.
sb := new MfText.StringBuilder()
value := new MfString("An ordinary string")
index := value.IndexOf("An ") + 3
capacity := 0xFFFF
; Instantiate a StringBuilder from a string.
sb1 := new MfText.StringBuilder(value)
SbAppendInfo(sb1, sb)
; Instantiate a StringBuilder from string and define a capacity.
sb2 := new MfText.StringBuilder(value, capacity)
SbAppendInfo(sb2, sb)
; Instantiate a StringBuilder from substring and define a capacity.
sb3 := new MfText.StringBuilder(value, index
,value.Length - index
,capacity)
SbAppendInfo(sb3, sb)
MsgBox % sb.ToString()
/*
Value: An ordinary string
Capacity: 18 MaxCapacity: 2147483647 Length: 18
Value: An ordinary string
Capacity: 65535 MaxCapacity: 2147483647 Length: 18
Value: ordinary string
Capacity: 65535 MaxCapacity: 2147483647 Length: 15
*/
SbAppendInfo(sbIn, sbOut)
{
sbOut.AppendFormat("Value: {0}{1}", sbIn, MfEnvironment.Instance.NewLine)
sbOut.AppendFormat("Capacity: {0:i} MaxCapacity: {1:i} Length: {2:i}", sbIn.Capacity, sbIn.MaxCapacity, sbIn.Length)
sbOut.AppendLine()
sbOut.AppendLine()
}
Most 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:
1) You can make individual method calls and ignore the return value, as the following example does.
sb := new MfText.StringBuilder()
sb.Append("This is the beginning of a sentence, ")
sb.Replace("the beginning of ", "")
sb.Insert(sb.ToString(true).IndexOf("a ") + 2, "complete ")
sb.Replace(",", ".")
MsgBox % sb.ToString() ; This is a complete sentence.
2) You can make a series of method calls in a single statement. This can be convenient if you want to write a single statement that chains successive operations. The following example consolidates three method calls from the previous example into a single line of code.
sb := new MfText.StringBuilder()
MsgBox % sb.Append("This is the beginning of a sentence, ")
.Replace("the beginning of ", "")
.Insert(sb.ToString(true).IndexOf("a ") + 2, "complete ").Replace(",", ".")
.ToString() ; This is a complete sentence.
Performing StringBuilder operations
You can use the methods of the StringBuilder class to iterate, add, delete, or modify characters in a StringBuilder object.
Iterating StringBuilder characters
You can access the characters in a StringBuilder object by using the StringBuilder.Chars property. 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 MfUnicodeCategory.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.
sb := new MfText.StringBuilder()
sb1 := new MfText.StringBuilder()
; Generate 10 random numbers and store them in a StringBuilder.
ctr := 0
While (ctr <= 9)
{
sb1.Append(Mfunc.Random()).Append(",")
ctr++
}
sb1.Length-- ; remove last ,
sb.AppendLine("The original string:")
sb.AppendLine(sb1.ToString())
; Decrease each number by one.
ctr := 0
While (ctr < sb1.Length)
{
if (MfChar.GetUnicodeCategory(sb1.Chars[ctr]).Equals(MfUnicodeCategory.Instance.DecimalDigitNumber))
{
number := MfChar.GetNumericValue(sb1.Chars[ctr])
number--
if (number < 0)
number := 9
sb1.Chars[ctr] := new MfString(number, true).Index[0]
}
ctr++
}
sb.AppendLine("The new string:")
sb.AppendLine(sb1.ToString())
MsgBox % sb.ToString()
/*
The original string:
26850403,107280301,1550505509,841162532,623723528,1192182565,181914076,799185027,1940502902,2107953480
The new string:
15749392,096179290,0449494498,730051421,512612417,0081071454,070803965,688074916,0839491891,1096842379
*/
Adding text to a StringBuilder object
The StringBuilder class includes the following methods for expanding the contents of a StringBuilder object:
sb := new MfText.StringBuilder()
sb1 := new MfText.StringBuilder()
sb1.Append("*", 10).Append(" Adding Text to a StringBuilder Object ").Append("*", 10)
sb1.AppendLine("`r`n")
sb1.AppendLine("Some code points and their corresponding characters:")
;Append some formatted text.
ctr := 50
While (ctr < 60)
{
sb1.AppendFormat("{0:#12X} {1:12c}", ctr, ctr)
sb1.AppendLine()
ctr++
}
pos := sb1.ToString(true).IndexOf("characters:") + 11 + StrLen(MfEnvironment.Instance.NewLine)
; Insert a column header.
sb1.Insert(pos, MfString.Format("{2}{0:12} {1:12}{2}", "Code Unit", "Character", MfEnvironment.Instance.NewLine))
sb.Append(sb1.ToString())
MsgBox % sb.ToString()
/*
********** Adding Text to a StringBuilder Object **********
Some code points and their corresponding characters:
Code Unit Character
0X32 2
0X33 3
0X34 4
0X35 5
0X36 6
0X37 7
0X38 8
0X39 9
0X3A :
0X3B ;
*/
Deleting text from a StringBuilder object
The 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.
sb := new MfText.StringBuilder()
sb1 := new MfText.StringBuilder("A StringBuilder object")
SbInfo(sb1, sb)
; Remove "object" from the text.
textToRemove := new MfString("object")
pos := sb1.ToString(true).IndexOf(textToRemove)
if (pos >= 0) {
sb1.Remove(pos, textToRemove.Length)
SbInfo(sb1, sb)
}
; Clear the StringBuilder contents.
sb1.Clear()
SbInfo(sb1, sb)
MsgBox % sb.ToString()
/*
Value: A StringBuilder object
Capacity: 22 MaxCapacity: 2147483647 Length: 22
Value: A StringBuilder
Capacity: 22 MaxCapacity: 2147483647 Length: 16
Value:
Capacity: 22 MaxCapacity: 2147483647 Length: 0
*/
SbInfo(sbIn, sbOut)
{
sbOut.AppendFormat("Value: {0}{1}", sbIn, MfEnvironment.Instance.NewLine)
sbOut.AppendFormat("Capacity: {0:i} MaxCapacity: {1:i} Length: {2:i}", sbIn.Capacity, sbIn.MaxCapacity, sbIn.Length)
sbOut.AppendLine()
sbOut.AppendLine()
}
Modifying the text in a StringBuilder object
The 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.
sb := new MfText.StringBuilder("Hello World!")
sb.Replace("!", "?")
MsgBox % sb.ToString() ; Hello World?
Searching the text in a StringBuilder object
The StringBuilder class does not include methods similar to the MfString.Contains, MFString.IndexOf, and MfString.StartsWith methods provided by the MfString 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.
Technique |
Pros |
Cons |
Search string values before adding them to the StringBuilder object. |
Useful for determining whether a substring exists. |
Cannot be used when the index position of a substring is important. |
Easy to use if you assign all the text to a StringBuilder object, and then begin to modify it. |
Cumbersome to repeatedly call ToString if you must make modifications before all text is added to the StringBuilder object. You must remember to work from the end of the StringBuilder object's text if you're making changes. |
|
Use the Chars property to sequentially search a range of characters. |
Useful if you're concerned with individual characters or a small substring. |
Cumbersome if the number of characters to search is large or if the search logic is complex. |
Convert the StringBuilder object to a MfString object, and perform modifications on the MfString object. |
Useful if the number of modifications is small. |
Negates the performance benefit of the StringBuilder class if the number of modifications is large. |
sb := new MfText.StringBuilder()
sb1 := new MfText.StringBuilder("ABC", 50)
; Append three characters (D, E, and F) to the end of the StringBuilder.
lst := MfCharList.FromString("DEF")
sb1.Append(lst)
; Append a format string to the end of the StringBuilder.
sb1.AppendFormat("GHI{0}{1}", "J", MFChar.FromCharCode(107))
sb.AppendLine(MfString.Format("{0} chars: {1}", sb1.Length, sb1.ToString()))
; Insert a string at the beginning of the StringBuilder.
sb1.Insert(0, "Alphabet: ")
; Replace all lowercase k's with uppercase K's.
sb1.Replace("k", "K")
sb.Append(sb1.ToString())
MsgBox % sb.ToString()
/*
11 chars: ABCDEFGHIJk
Alphabet: ABCDEFGHIJK
*/