In the first part of this series, we explored many foundational string methods such as Substring, IndexOf, Replace, and others. This second part dives deeper into more advanced and less commonly discussed methods of the System.String class, as well as important related functionality in string manipulation. Mastery of these methods will enhance your ability to handle complex text processing tasks efficiently in C#.
The static String.Compare() method compares two strings and returns an integer indicating their relative position in the sort order.
Return values:
int result = String.Compare("apple", "banana"); // result < 0 since "apple" < "banana"
int resultIgnoreCase = String.Compare("apple", "APPLE", StringComparison.OrdinalIgnoreCase); // 0 (equal ignoring case)
StringComparison enumeration allows fine control of comparison rules, such as culture-aware or ordinal comparisons.
Instance method CompareTo() compares the current string to another string, returning the same type of integer result as Compare().
string a = "cat";
string b = "dog";
int compare = a.CompareTo(b); // < 0 because "cat" < "dog"
The Equals() method compares two strings for equality. It has several overloads, allowing you to specify case sensitivity and culture rules.
string s1 = "Hello";
string s2 = "hello";
bool equal1 = s1.Equals(s2); // false (case sensitive)
bool equal2 = s1.Equals(s2, StringComparison.OrdinalIgnoreCase); // true
Unlike the == operator, Equals() provides more overloads and control over comparison options.
This static method checks if a string is either null or empty ("").
string s1 = null;
string s2 = "";
string s3 = " ";
bool check1 = String.IsNullOrEmpty(s1); // true
bool check2 = String.IsNullOrEmpty(s2); // true
bool check3 = String.IsNullOrEmpty(s3); // false, because s3 contains a space
This method extends IsNullOrEmpty() by returning true if the string is null, empty, or consists only of whitespace characters.
string s4 = " ";
bool check4 = String.IsNullOrWhiteSpace(s4); // true
These methods are invaluable for input validation and cleaning user inputs.
These methods add padding characters to the left or right of a string until it reaches a specified total length.
string str = "123";
string paddedLeft = str.PadLeft(5, '0'); // "00123"
string paddedRight = str.PadRight(5, '*'); // "123**"
If the original string is already longer than the specified length, it is returned unchanged.
Removes characters from a string starting at a specified index, optionally for a specified count.
string original = "Hello World!";
string removed1 = original.Remove(5); // "Hello"
string removed2 = original.Remove(5, 6); // "Hello!"
Inserts a string at a specified index into the current string.
string baseStr = "Hello!";
string inserted = baseStr.Insert(5, " World"); // "Hello World!"
The index must be between 0 and the length of the string (inclusive), otherwise an ArgumentOutOfRangeException is thrown.
The Normalize() method converts a string to a specified Unicode normalization form, which is essential when comparing strings containing accented characters or composed/uncomposed characters.
string accented = "e\u0301"; // 'e' + combining acute accent
string normalized = accented.Normalize(NormalizationForm.FormC);
bool areEqual = normalized == "\u00E9"; // true, 'é' as single character
Converts the string into an array of characters, enabling iteration or manipulation of individual characters.
string greeting = "Hi!";
char[] chars = greeting.ToCharArray();
foreach(char c in chars) {
Console.WriteLine(c);
}
// Output:
// H
// i
// !
Although not a method of String itself, string interpolation and formatting are essential for dynamic string creation.
Introduced in C# 6.0, string interpolation provides an easy-to-read syntax to embed expressions inside string literals.
string name = "Alice";
int age = 30;
string greeting = $"Hello, {name}. You are {age} years old.";
// Output: "Hello, Alice. You are 30 years old."
The static method String.Format() formats strings using placeholders.
string formatted = String.Format("Hello, {0}. Today is {1:D}.", name, DateTime.Now);
// Output example: "Hello, Alice. Today is Sunday, May 24, 2025."
Since strings are immutable, every operation that changes a string produces a new string object, which can impact memory and CPU performance when done excessively inside loops or large-scale text processing.
To optimize, use StringBuilder when performing many concatenations or manipulations, and prefer methods that avoid unnecessary string copies. Always be mindful of the trade-offs between readability, maintainability, and performance.
| Method | Description | Example Usage |
|---|---|---|
| Compare() | Compares two strings, returns integer indicating order. | String.Compare("a", "b") < 0 |
| CompareTo() | Instance comparison of current string with another. | "cat".CompareTo("dog") < 0 |
| Equals() | Checks if strings are equal with case/culture options. | s1.Equals(s2, StringComparison.OrdinalIgnoreCase) |
| IsNullOrEmpty() | Checks if string is null or empty. | String.IsNullOrEmpty(s) |
| IsNullOrWhiteSpace() | Checks if string is null, empty, or whitespace. | String.IsNullOrWhiteSpace(s) |
| PadLeft() | Adds padding characters on the left. | "123".PadLeft(5, '0') // "00123" |
| PadRight() | Adds padding characters on the right. | "123".PadRight(5, '*') // "123**" |
| Remove() | Removes characters from a string. | "Hello World".Remove(5,6) // "Hello" |
| Insert() | Inserts a string at specified index. | "Hello!".Insert(5, " World") // "Hello World!" |
| Normalize() | Normalizes Unicode strings. | s.Normalize(NormalizationForm.FormC) |
| ToCharArray() | Converts string to char array. | "Hi".ToCharArray() |
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved