16.13. Insert, Remove and Replace Methods of Class StringBuilderClass StringBuilder provides 18 overloaded Insert methods to allow values of various types to be inserted at any position in a StringBuilder. There are versions of Insert for each of the primitive types and for character arrays, Strings and Objects. Each version takes its second argument, converts it to a String and inserts the String into the StringBuilder at the index specified by the first argument. The index must be greater than or equal to 0 and less than the length of the StringBuilder; otherwise, an ArgumentOutOfRangeException occurs. Class StringBuilder also provides method Remove for deleting characters in a StringBuilder. Method Remove takes two argumentsthe index at which to begin deletion and the number of characters to delete. The sum of the starting subscript and the number of characters to be deleted must always be less than the StringBuilder's length; otherwise, an ArgumentOutOfRangeException occurs. Figure 16.13 demonstrates the Insert and Remove methods. Lines 2037 use nine different overloaded Insert methods to insert the String representations of the variables created in lines 717 at index 0 in the StringBuilder. Figure 16.13. StringBuilder text insertion and removal.
Another useful StringBuilder method is Replace, which searches for a specified String or character and substitutes another String or character in its place. Figure 16.14 demonstrates Replace. Figure 16.14. StringBuilder text replacement.
Line 13 uses method Replace to replace all instances of the String "Jane" with the String "Greg" in builder1. An overloaded version of this method takes two characters as parameters and replaces each occurrence of the first character with the second character. Line 14 uses an overload of Replace that takes four parameterstwo characters and two Integers. The method replaces all instances of the first character with the second character, beginning at the index specified by the first Integer and continuing for a count specified by the second Integer. In this case, Replace looks at only five characters, starting with the character at index 0. As the output illustrates, this version of Replace replaces g with G in the word "good", but not in "greg"the gs in "greg" are not in the range indicated by the Integer arguments (i.e., between indexes 0 and 4). |