.NET Documentation

String Manipulation in .NET

The System.String class in .NET represents a sequence of Unicode characters. Strings are immutable, meaning once a string object is created, its value cannot be changed. Operations that appear to modify a string actually create a new string object with the modified value.

Key String Operations

Concatenation

Combining strings is a common operation. .NET provides several efficient ways to do this:

  • string.Concat(): A static method for concatenating strings.
  • The + operator: Syntactic sugar that often gets compiled into more efficient methods like string.Concat or StringBuilder.
  • string.Format(): Useful for embedding values into a template string.
  • StringBuilder class: Ideal for scenarios where you need to perform many string modifications, as it's more performant than repeatedly creating new string objects.

Example:

string firstName = "Jane";
string lastName = "Doe";
string fullName = string.Concat(firstName, " ", lastName);
Console.WriteLine(fullName); // Output: Jane Doe

string message = string.Format("Hello, {0}!", fullName);
Console.WriteLine(message); // Output: Hello, Jane Doe!

StringBuilder sb = new StringBuilder();
sb.Append("This is ");
sb.Append("a ");
sb.Append("long ");
sb.Append("string.");
Console.WriteLine(sb.ToString()); // Output: This is a long string.
                    

Comparison

Comparing strings involves checking for equality or ordering. Be mindful of case sensitivity and culture-specific rules.

  • string.Equals(): Compares two strings for equality. Overloads allow specifying case sensitivity and culture.
  • The == and != operators: Provide a concise way to check for string equality. Internally, they often call string.Equals.
  • string.Compare(): Compares two strings lexicographically and returns an integer indicating their relative order.
  • string.CompareTo(): An instance method that compares the current string to another string.

Example:

string s1 = "Hello";
string s2 = "hello";

bool areEqualCaseSensitive = s1.Equals(s2, StringComparison.Ordinal); // false
bool areEqualCaseInsensitive = s1.Equals(s2, StringComparison.OrdinalIgnoreCase); // true

int comparisonResult = string.Compare(s1, s2, StringComparison.OrdinalIgnoreCase); // 0 (equal)
                    

Searching and Indexing

Locating substrings within a string is frequently needed.

  • string.Contains(): Checks if a string contains a specified substring.
  • string.IndexOf(): Returns the zero-based index of the first occurrence of a specified substring. Returns -1 if not found.
  • string.LastIndexOf(): Returns the zero-based index of the last occurrence of a specified substring.

Example:

string sentence = "The quick brown fox jumps over the lazy dog.";
bool containsFox = sentence.Contains("fox"); // true
int indexOfFox = sentence.IndexOf("fox"); // 16
int lastIndexOfThe = sentence.LastIndexOf("the"); // 35 (case-sensitive)
                    

Substrings and Extraction

Extracting parts of a string is fundamental.

  • string.Substring(): Extracts a substring from the current string.
  • string.Split(): Splits a string into substrings based on specified delimiters.
  • ``: Slicing strings (available in C# 8.0 and later) for more flexible substring extraction.

Example:

string data = "apple,banana,cherry";
string part = sentence.Substring(4, 5); // "quick"
string[] fruits = data.Split(','); // ["apple", "banana", "cherry"]
string slice = sentence[^4..^0]; // " dog." (using range operator)
                    

Modification and Transformation

While strings are immutable, common transformations return new strings.

  • string.Replace(): Returns a new string in which all occurrences of a specified string are replaced.
  • string.Trim(): Removes all occurrences of a set of specified characters from the beginning and end of the current string. Variations include TrimStart() and TrimEnd().
  • string.ToUpper() / string.ToLower(): Converts the string to uppercase or lowercase.
  • string.Insert(): Inserts a string into another string at a specified index.
  • string.Remove(): Removes a specified number of characters from a string starting at a specified index.

Example:

string original = "  Example String  ";
string trimmed = original.Trim(); // "Example String"
string replaced = original.Replace("Example", "Sample"); // "  Sample String  "
string upper = original.ToUpper(); // "  EXAMPLE STRING  "