Back when I talked about strings, I mentioned how they are immutable. This means that once a string is created you cannot change it. When you desire to make changes to a string you can either remake the string or use the string builder class.
Creating a String Builder
To create a string builder simply use the String Builder constructor passing to it the original string that you want to represent.
Example:
StringBuilder s = new StringBuilder("welcome to codecall");
If you do Console.WriteLine(s) the output will be welcome to codecall.
Appending Characters
There are several ways of appending characters to the end of a string builder. The simple method is to just add one character to the end of the string builder.
Example:
s.Append('x');
Console.WriteLine(s);
The output will be:
Quote
welcome to codecallx
We can also add a character more than one time. Using the method overload Append(char, int) we specify a char and the number of times to append it to the end of the string.
Example:
s.Append('x', 3);
This will add 3 x’s to the end of s.
Appending Strings
Two more overloads of append are:
- Append(char[])
- Append(string)
The first overload adds the contents of a character array to the end of the string.
Example:
StringBuilder s = new StringBuilder("welcome to codecall");
s.Append(new[] {'a', 'b', 'c'});
Console.WriteLine(s);
The output is:
Quote
welcome to codecallabc
A neat fact to note here is how we didn’t have to specify the type of array. C# is smart enough to figure out that this is a character array. Occasionally I may use var for variable declarations because C# is smart enough to figure out the type of variable based on its usage.
You can also append a string like this:
StringBuilder s = new StringBuilder("welcome to codecall");
s.Append("abc");
Console.WriteLine(s);
Replacing Characters
The Replace methods replaces all instances of a character with a new character. Example:
StringBuilder s = new StringBuilder("welcome to codecall");
s = s.Replace('e', 'o');
Console.WriteLine(s);
The output of this code is:
Quote
wolcomo to codocall
Deleting Characters
The method to delete characters is Remove(startIndex, length). When using this method it is important to make sure that startIndex actually references a character in the string and that there are length-1 characters after startIndex. If this isn’t true then you’re program is going to crash.
Example:
s = s.Remove(5, 3);
This code deletes the characters at index 5, 6 and 7. Then the new string builder is produced without these characters.
The output will be:
Quote
welcoto codecall
Adding Characters
To add characters we use the Insert method.
Example:
s = s.Insert(5, 'C');
This code inserts character C at index 5. Whatever was at index 5 and above gets pushed over one to make room for the new character.
Output is then:
Quote
welcoCme to codecall


Sign In
Create Account


Back to top









