System.Text Namespace
Provides fundamental classes that represent characters, strings, and the various encodings that strings use to be represented in memory and in files.
Classes
- Encoding Represents a character encoding.
- Decoder Decodes a sequence of byte arrays into a sequence of characters.
- Encoder Encodes a sequence of characters into a sequence of byte arrays.
- StringBuilder Represents a mutable sequence of characters.
- NormalizationForm Specifies the Unicode normalization form to use.
Abstract Classes
Interfaces
Commonly Used Classes
The System.Text
namespace includes several important classes for text manipulation:
StringBuilder
The StringBuilder
class is used to create mutable strings. It's more efficient than repeatedly concatenating strings in a loop.
using System.Text;
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(", ");
sb.Append("World!");
string result = sb.ToString();
Console.WriteLine(result); // Output: Hello, World!
Encoding
The Encoding
class and its derived classes (e.g., UTF8Encoding
, ASCIIEncoding
) are used to convert strings into byte arrays and vice versa, supporting various character encodings.
using System.Text;
string text = "Hello, .NET!";
byte[] utf8Bytes = Encoding.UTF8.GetBytes(text);
string decodedText = Encoding.UTF8.GetString(utf8Bytes);
Console.WriteLine(decodedText); // Output: Hello, .NET!