String Operations
Explore essential string operations in C# to compare, combine, search, and modify text efficiently. Learn techniques for culture-aware comparisons, string interpolation, trimming, splitting, and case changes to handle strings effectively in your .NET applications.
The System.String class provides dozens of built-in methods. Let's look at some of the most critical operations that we can perform on string objects.
Compare
We can compare the equality of strings or their alphabetical ordering. To check alphabetical sequence, we use the CompareTo() method.
Lines 1–2: We define two separate string variables representing names.
Lines 5–6: We evaluate if both strings are identical and print the resulting boolean value.
Lines 12–15: We execute
CompareTo()to check alphabetical ordering. This prints a negative number since “Anna” comes before “Darcy”.Lines 17–21: We update the second name to “Albert” and compare again. This yields a positive integer because “Anna” comes after “Albert”.
Culture-aware comparisons
Using the == operator performs an exact, case-sensitive match. When we need to compare strings without case sensitivity, we should avoid converting both strings using .ToLower() or .ToUpper(). Creating new strings just for comparison wastes memory. Instead, we use the string.Equals() method combined with the StringComparison.OrdinalIgnoreCase enumeration.
Lines 1–2: We define two strings with identical text but different casing.
Line 5: We show the inefficient approach. Calling
ToLower()allocates two completely new string objects in memory just to perform a check.Line 6: We print the result of the inefficient match.
Line 9: We use
string.EqualswithStringComparison.OrdinalIgnoreCaseto perform a direct, allocation-free comparison.Line 10: We print the result of our secure, ...
Here is how we can implement these different combining techniques.
Lines 1–2: ...