What is the purpose of StringBuilder class in C#?

WBOY
Release: 2023-09-09 16:53:02
forward
934 people have browsed it

C# 中 StringBuilder 类的用途是什么?

In C#, strings are immutable. This means that the string cannot be modified once created. Any modification to the string returns a new string containing the modifications, while the original string remains unchanged.

string word = "aaabbbccc";
string newWord = word.Replace('b', 'd');
Console.WriteLine(word); // prints aaabbbccc
Console.WriteLine(newWord); // prints aaadddccc
Copy after login

The StringBuilder class represents a string-like object that can be modified, that is, a mutable string. It is implemented differently from the string type, which represents an immutable string.

Because modifying a string object creates a copy, repeated modifications to the string object may result in performance losses. For small repetitions it is negligible, but for large loops it can be significant. StringBuilder provides an efficient alternative to modifying strings by appending, deleting, replacing, or inserting characters.

StringBuilder maintains an internal buffer to hold characters. If there is free space in the buffer, new data is appended. Otherwise, it creates a new buffer, copies the old data to the new buffer, and then appends the data.

var sb = new StringBuilder();
for (int i = 0; i < 10; i++){
   sb.Append("a");
}
Console.WriteLine(sb.ToString()); // prints aaaaaaaaaa
Copy after login

The following are the different ways to construct a StringBuilder object.

// Initialize a new instance of StringBuilder
var sb1 = new StringBuilder();

// Initialize a new instance of StringBuilder using the given capacity
var sb2 = new StringBuilder(capacity: 10);

// Initialize a new instance of StringBuilder with the given string
var sb3 = new StringBuilder(value: "Hello World");

// Initialize a new instance of StringBuilder with the given capacity and the maximum capacity it can grow to
var sb4 = new StringBuilder(capacity: 20, maxCapacity: 10);

// Initialize a new instance of StringBuilder with the given string and capacity
var sb5 = new StringBuilder(value: "Hello", capacity: 20);

// Initialize a new instance of StringBuilder from the given substring and capacity
var sb6 = new StringBuilder(value: "Hello World", startIndex: 0, length: 5, capacity: 20);
Copy after login

The StringBuilder class has a Length property that indicates the number of characters the object currently has. As more characters are added to an object, its length increases until it reaches its capacity, which defines the maximum number of characters the object can currently contain.

If the number of added characters causes the length to exceed its current capacity, the class allocates new memory, coupling its capacity. The new character is then added to the object and its Length property is adjusted.

StringBuilder continues to dynamically add additional memory until the value of the MaxCapacity property is reached. After that, no more memory can be allocated for the object. If you try to add more data to the object, an ArgumentOutOfRangeException or OutOfMemoryException exception is thrown.

StringBuilder provides the following methods to easily modify strings.

  • #Append - Appends the string representation of the specified object to this instance.

  • AppendFormat< /strong> - Appends the string returned by processing a composite format string (containing zero or more format items) to this instance. Each format item is replaced by the string representation of the corresponding object parameter.

  • AppendJoin - Joins string representation objects of the elements in the provided arrays, using the specified delimiter between each member, and appends the result to The current instance of the string builder.

  • AppendLine - Appends the default line terminator to the end of the current StringBuilder object.

  • Clear - Removes all characters from the current StringBuilder instance.

  • CopyTo - Copies characters to a target character range or character array.

  • EnsureCapacity − Ensures that the capacity of this StringBuilder instance is at least the specified value.

  • Equals − Returns true if this instance and the provided instance have equal string, Capacity and MaxCapacity values.

  • GetChunks - Returns an object that can be used to iterate over chunks of characters.

  • Insert - Inserts the string representation of the specified object into this instance at the specified character position.

  • Delete - Removes the specified range of characters from this instance.

  • Replace - Replaces all occurrences of the specified character or string in this instance with another specified character or string.

  • ToString - Converts the current instance to a string.

Example

Live demonstration

using System;
using System.Text;
class Program{
   static void Main(string[] args){
      string word = "aaabbbccc";
      string newWord = word.Replace(&#39;b&#39;, &#39;d&#39;);
      Console.WriteLine(word); // prints aaabbbccc
      Console.WriteLine(newWord); // prints aaadddccc
      var sb = new StringBuilder();
      for (int i = 0; i < 10; i++){
         sb.Append("a");
      }
      Console.WriteLine(sb.ToString()); // prints aaaaaaaaaa

      // Initialize a new instance of StringBuilder
      var sb1 = new StringBuilder();

      // Initialize a new instance of StringBuilder using the given capacity
      var sb2 = new StringBuilder(capacity: 10);
     
      // Initialize a new instance of StringBuilder with the given string
      var sb3 = new StringBuilder(value: "Hello World");
      // Initialize a new instance of StringBuilder with the given capacity and the    maximum capacity it can grow to
      var sb4 = new StringBuilder(capacity: 20, maxCapacity: 50);
      // Initialize a new instance of StringBuilder with the given string and capacity
      var sb5 = new StringBuilder(value: "Hello", capacity: 20);

      // Initialize a new instance of StringBuilder from the given substring and capacity
      var sb6 = new StringBuilder(value: "Hello World", startIndex: 0, length: 5, capacity: 20);
   }
}
Copy after login

Output

aaabbbccc
aaadddccc
aaaaaaaaaa
Copy after login

The above is the detailed content of What is the purpose of StringBuilder class in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template