System.Text Namespace
The System.Text namespace contains types that represent various kinds of string representations, character encodings, and string manipulation classes.
Key Classes
Encoding
Provides information about a specific character encoding, such as ASCII, UTF-8, or UTF-16. This class is fundamental for converting between strings and byte arrays.
StringBuilder
Represents a mutable sequence of characters. This class is useful for efficiently building strings when many modifications are needed, as it avoids the overhead of creating new string objects for each change.
Common Operations
Encoding and Decoding Text
Encoding classes are used to convert strings to byte arrays (encoding) and byte arrays back to strings (decoding). This is crucial for reading and writing data to files, network streams, or databases, especially when dealing with different character sets.
Example: UTF-8 Encoding
// Encode a string to a byte array using UTF-8
string original = "Hello, World!";
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(original);
// Decode a byte array back to a string
string decoded = System.Text.Encoding.UTF8.GetString(utf8Bytes);
Console.WriteLine(decoded); // Output: Hello, World!
String Manipulation with StringBuilder
When performing numerous string concatenations or modifications, using StringBuilder is significantly more performant than repeated string concatenation with the + operator.
Example: Using StringBuilder
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("This is the first part.");
sb.AppendLine();
sb.Append("And this is the second part.");
sb.Replace("second", "second-most");
string result = sb.ToString();
Console.WriteLine(result);