C#. Class StringBuilder. Methods of StringBuilder class. Examples

Class StringBuilder. Methods of StringBuilder class. Examples


Contents


1. Features of the StringBuilder class. Comparing StringBuilder and String classes

As you know, in the C# programming language, the string type is introduced to work with strings, which corresponds to the System.String (String) class. However, when working with strings intensively, it is more advisable to use the System.Text.StringBuilder class, which provides better performance compared to the String class.

The difference between the String and StringBuilder classes is as follows.

In the case of the class of String, when assignment operation executed =

// memory allocation for the string literal "Text1"
string s = "Text1";

// reallocation of memory
s = "Text2";

the memory for the new string literal (“Text2”) is reallocated in a new way: a new piece of memory is allocated to which the new changed string is copied. The memory allocated for the previous fragment is subsequently destroyed by the Garbage collector.

In the StringBuilder class, when changing the original string, memory for the new string is allocated only when the size of the new string is larger than the size of the original string. In this case, memory is allocated to twice the previous size. If the size of the new string is less than or equal to the size of the original string, then the memory is not reallocated. This mechanism allows you to increase performance by reducing the intensity (quantity) of the allocation of new resources and the release of used resources.

Conclusion: when working intensively with strings, it is recommended to use the StringBuilder class, in other cases, it is recommended to use the String (or string) class.

 

2. In which namespace is the StringBuilder class declared?

To use the abbreviated name of the StringBuilder class, you must first connect the System.Text namespace

using System.Text;

However, you can directly access the class name using the System.Text.StringBuilder string.

 

3. Assignment operation = for StringBuilder Class

In the System.Text.StringBuilder class, the assignment operator is not defined. Therefore, when declaring an object of class StringBuilder

StringBuilder sb = new StringBuilder();

use the assignment operator = to assign a value to the object

sb = "Hello world!"; // Compilation error

will fail. In this case, the compiler will throw an error

Cannot implicitly convert type 'string' to System.String.StringBuilder

 

4. The operation of assignment a single character by index in the String and StringBuilder classes

There is a difference between the System.String and System.Text.StringBuilder classes when using the single character index assignment operation.

A variable (object) of type String cannot be assigned a single character by index as shown below

string s = "Some text";
s[5] = 'n'; // compilation error

A single character can only be read

string s = "Some text";
char c = s[5]; // c = 't'

Unlike the String type, for the StringBuilder type, a single character can be changed by its index. For example

StringBuilder sb = new StringBuilder("Some text");
sb[5] = 'n'; // OK!


 

5. Creating an object of class StringBuilder. Examples

The StringBuilder class has several constructors that allocate memory and also initialize instances of this class. The following are examples of creating instances of StringBuilder class (objects)

using System.Text;

...

// 1. Creating an instances of StringBuilder class (objects)
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder(10); // string up to 10 characters
StringBuilder sb3 = new StringBuilder("Hello world!"); // constant string

...

 

6. Methods of StringBuilder class

This section describes the methods of the StringBuilder class that are used most often.

6.1. Method Append(). Add data to current instance

The Append() method is intended to add a copy of an instance of some type to the current instance. The method has many overloaded implementations for different types.

The following are fragments of some implementations of the Append() method.

// Append() method - add data of any of the standard types
// 1. Add string of type String
StringBuilder sb = new StringBuilder("Hello ");
sb.Append("world!");
Console.WriteLine("sb = {0}", sb); // sb = Hello world!

// 2. Add string of type StringBuilder
StringBuilder sb2 = new StringBuilder("abc");
StringBuilder sb3 = new StringBuilder("def");
sb2.Append(sb3);
Console.WriteLine("sb2 = {0}", sb2); // sb2 = abcdef

// 3. Add the number of type double
StringBuilder sb4 = new StringBuilder("Pi = ");
double Pi = 3.141592;
sb4.Append(Pi);
Console.WriteLine("{0}", sb4); // Pi = 3.141592

// 4. Add variable of type bool
StringBuilder sb5 = new StringBuilder();
sb5.Append(true);
Console.WriteLine("sb5 = {0}", sb5); // sb5 = True

 

6.2. Change a single character in a string. Access by index

Unlike the string type, in the StringBuilder class you can change a single character by its index. For example

// You can change a single character of a string (unlike String type)
StringBuilder sb = new StringBuilder("Text.");
sb[0] = 'N';
Console.WriteLine("sb = {0}", sb); // sb = Next.

 

6.3. Method Insert()

The Insert() method is implemented to insert objects of different types at a given position in the string. The method has many overloaded implementations. In all implementations, the first parameter of the method sets the insertion position.

Example.

// Insert() method - inserts data into the source string from a given position
// 1. Insert an object of type string
StringBuilder sb1 = new StringBuilder("abcdef");
StringBuilder sb2 = sb1.Insert(1, "---");
Console.WriteLine("sb1 = {0}", sb1); // sb1 = a---bcdef
Console.WriteLine("sb2 = {0}", sb2); // sb2 = a-- - bcdef

// 2. Insert an object of type int
StringBuilder sb3 = new StringBuilder("Max = ");
sb3.Insert(sb3.Length, "256");
Console.WriteLine("{0}", sb3); // Max = 256

// 3. Insert an object of type double
StringBuilder sb4 = new StringBuilder();
sb4.Insert(0, Math.PI);
Console.WriteLine("Pi = {0}", sb4); // Pi = 3.141592653589793

 

6.4. Method Remove(). Remove a character range from the source string

The Remove() method is used to remove a range of characters from a given string starting at a given position. The method takes two integer parameters. The first parameter indicates the start index from which the string is removed. The second parameter indicates the number of characters to delete.

Example.

// Remove() method - removes a range of characters from the source string
StringBuilder sb = new StringBuilder("abcdefghi");
sb.Remove(2, 3); // delete "cde"
Console.WriteLine("sb = {0}", sb); // sb = abfghi

StringBuilder sb2 = new StringBuilder("01234567890");
sb2.Remove(0, 5);
Console.WriteLine("sb2 = {0}", sb2); // sb2 = 567890

 

6.5. Method Replace(). Replaces a character/substring in the source string

The Replace() method is used to replace a substring in a string. The method works both for single characters and for strings. The method has several overloaded implementations, among which there are four of the following:

  • replacing one char character with another char character;
  • replacing of one char type character with another char type character starting from a given position and in a given range;
  • replacing one string of type string with another string of type string;
  • replacing one string of type string with another string of type string starting at a given position and in a given range.

Example.

// Replace() method - replaces a character/substring in the source string
// with the specified character/substring

// 1. Implementation of Replace(char, char) - replacing one character with another
StringBuilder sb = new StringBuilder("Solution");
sb.Replace('o', '+');
Console.WriteLine("sb = {0}", sb); // sb = S+luti+n

// 2. Implementation Replace(char, char, int, int)
StringBuilder sb2 = new StringBuilder("0123456789");

// Replacing character '2' to '0'
// scan of string starts from position 0 to position 3
sb2.Replace('2', '+', 0, 3); // sb2 = 01+3456789
Console.WriteLine("sb2 = {0}", sb2);

// Write new value to string
sb2.Clear();
sb2.Insert(0, "200+20+2=222");

// replace all characters '2' in the string with characters '3'
sb2.Replace('2', '3', 0, sb2.Length);
Console.WriteLine("sb2 = {0}", sb2); // sb2 = 300+30+3=333

// 3. Implementation Replace(string, string)
StringBuilder sb3 = new StringBuilder("abcdef abcdef");
sb3.Replace("bcd", "AAA"); // replace all occurrences of "bcd" with "AAA"
Console.WriteLine("sb3 = {0}", sb3); // sb3 = aAAAef aAAAef

// 4. Implementation Replace(string, string, int, int)
StringBuilder sb4 = new StringBuilder("Hello Hello Hello");
sb4.Replace("Hello", "ABC", 0, sb4.Length);
Console.WriteLine("sb4 = {0}", sb4); // sb4 = ABC ABC ABC

sb4.Clear();
sb4.Append("1++2++3++4++5");
sb4.Replace("++", "--", 0, 7); // in the range from 0 to 7
Console.WriteLine("sb4 = {0}", sb4); // sb4 = 1--2--3++4++5

 

6.6. Method Clear(). Remove all characters from the string

The Clear() method implements clearing the string (deleting all characters in the string).

Example.

// Method Clear()
StringBuilder sb = new StringBuilder("This is a string.");
Console.WriteLine("sb = {0}", sb); // sb = This is a string.

// clear the string
sb.Clear();
Console.WriteLine("sb = {0}", sb); // sb =

 

6.7. Method CopyTo(). Copy string to the array of type char

The CopyTo() method copies characters from the source string to an array of type char (System.Char). The method receives 4 parameters that have the following purpose:

  • position in the source string (int type);
  • destination array (type char[]) into which characters of the source string are written character by character;
  • position in the destination array (int type) from which copying of characters from the source string begins;
  • the number of characters to be copied (int type).

Example.

// Method CopyTo() - copies the characters of the source string to an array of type Char
StringBuilder sb = new StringBuilder("abcdef");
char[] arr = new char[5]; // allocate memory for array arr

// copy string "bcd" to arr
// Parameters:
// 1 - starting position in the string sb;
// arr - destination array to which characters are copied
// 0 - position in arr from which characters from sb are written
// 3 - the number of characters that are copied from sb to arr
sb.CopyTo(1, arr, 0, 3); // arr = { 'b', 'c', 'd', '\0', '\0' }

// copy substring "cdef" to arr2
char[] arrC2 = new char[6];
sb.CopyTo(2, arrC2, 2, 4); // arrC2 = { '\0', '\0', 'c', 'd', 'e', 'f' }

// Dilplay the arr2[] string
for (int i = 0; i < arrC2.Length; i++)
{
  Console.WriteLine("arrc[{0}] = {1}", i, arrC2[i]);
}

 

6.8. Method ToString(). Convert a string of type StringBuilder to a string of type String

To convert a string of type StringBuilder to a string of type String, use the ToString() method, which is implemented in the System.Object class.

According to the .NET Framework documentation, the ToString() method has two implementations whose general form is as follows:

public override string ToString()
public string ToString(int startIndex, int length)

In the first implementation, a simple conversion of a string of type StringBuilder to a string of type String occurs. In the second implementation, a string is copied starting at position startIndex with a length characters.

Example.

// Method ToString() - converts object of type StringBuilder to type String
StringBuilder sb = new StringBuilder("Hello world!");

// Full string conversion
String s1 = sb.ToString();
Console.WriteLine("s1 = {0}", s1); // s1 = "Hello world!"

// Converting string starting at position 6,
// number of characters to be copied is equal to 5
String s2 = sb.ToString(6, 5); // s2 = "world"
Console.WriteLine("s2 = {0}", s2);

 

6.9. Properties Length, Capasity, MaxCapasity

The StringBuilder class implements three integer properties that define the characteristics of a string:

  • Length – current number of characters per string;
  • Capasity – the number of characters that can be placed in a string without additional memory allocation;
  • MaxCapasity – the maximum content of the string, which can be allocated.

Example.

// Properties Length, Capasity, MaxCapasity
StringBuilder sb = new StringBuilder("12345");
int len, capasity, maxCapasity;

// Length - current number of characters per string
len = sb.Length; // length = 5

// Capasity - the number of characters that can be placed in a string
//           without additional memory allocation
capasity = sb.Capacity; // capasity = 16

// MaxCapasity - the maximum content of the string that can be selected
maxCapasity = sb.MaxCapacity; // maxCapasity = 2147483647

 


Related topics