C# - Common String Methods - Part 2

Common String Methods Part 2 in C# 

Introduction

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#.

Overview of Topics Covered in Part 2

  • Compare() and CompareTo()
  • Equals() Method
  • IsNullOrEmpty() and IsNullOrWhiteSpace()
  • PadLeft() and PadRight()
  • Remove() Method
  • Insert() Method
  • Normalize() Method
  • ToCharArray() Method
  • String interpolation and formatting methods
  • Performance considerations

Compare() and CompareTo() Methods

Compare()

The static String.Compare() method compares two strings and returns an integer indicating their relative position in the sort order.

Return values:

  • < 0: strA is less than strB
  • 0: strings are equal
  • > 0: strA is greater than strB

Example:


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.

CompareTo()

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"
  

Equals() Method

The Equals() method compares two strings for equality. It has several overloads, allowing you to specify case sensitivity and culture rules.

Example:


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.

IsNullOrEmpty() and IsNullOrWhiteSpace()

IsNullOrEmpty()

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
  

IsNullOrWhiteSpace()

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.

PadLeft() and PadRight() Methods

These methods add padding characters to the left or right of a string until it reaches a specified total length.

Usage:


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.

Remove() Method

Removes characters from a string starting at a specified index, optionally for a specified count.

Overloads:

  • Remove(int startIndex): removes from startIndex to the end.
  • Remove(int startIndex, int count): removes count characters starting from startIndex.

Example:


string original = "Hello World!";
string removed1 = original.Remove(5);       // "Hello"
string removed2 = original.Remove(5, 6);    // "Hello!"
  

Insert() Method

Inserts a string at a specified index into the current string.

Example:


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.

Normalize() Method

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.

Normalization Forms:

  • FormC: Canonical Composition
  • FormD: Canonical Decomposition
  • FormKC: Compatibility Composition
  • FormKD: Compatibility Decomposition

Example:


string accented = "e\u0301";    // 'e' + combining acute accent
string normalized = accented.Normalize(NormalizationForm.FormC);
bool areEqual = normalized == "\u00E9";  // true, 'é' as single character
  

ToCharArray() Method

Converts the string into an array of characters, enabling iteration or manipulation of individual characters.

Example:


string greeting = "Hi!";
char[] chars = greeting.ToCharArray();

foreach(char c in chars) {
    Console.WriteLine(c);
}
// Output:
// H
// i
// !
  

String Interpolation and Formatting

Although not a method of String itself, string interpolation and formatting are essential for dynamic string creation.

String Interpolation

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."
  

String.Format()

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."
  

Performance Considerations

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.

Summary Table of Part 2 Methods

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()

logo

C#

Beginner 5 Hours

Common String Methods Part 2 in C# 

Introduction

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#.

Overview of Topics Covered in Part 2

  • Compare() and CompareTo()
  • Equals() Method
  • IsNullOrEmpty() and IsNullOrWhiteSpace()
  • PadLeft() and PadRight()
  • Remove() Method
  • Insert() Method
  • Normalize() Method
  • ToCharArray() Method
  • String interpolation and formatting methods
  • Performance considerations

Compare() and CompareTo() Methods

Compare()

The static String.Compare() method compares two strings and returns an integer indicating their relative position in the sort order.

Return values:

  • < 0: strA is less than strB
  • 0: strings are equal
  • > 0: strA is greater than strB

Example:

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.

CompareTo()

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"

Equals() Method

The Equals() method compares two strings for equality. It has several overloads, allowing you to specify case sensitivity and culture rules.

Example:

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.

IsNullOrEmpty() and IsNullOrWhiteSpace()

IsNullOrEmpty()

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

IsNullOrWhiteSpace()

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.

PadLeft() and PadRight() Methods

These methods add padding characters to the left or right of a string until it reaches a specified total length.

Usage:

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.

Remove() Method

Removes characters from a string starting at a specified index, optionally for a specified count.

Overloads:

  • Remove(int startIndex): removes from startIndex to the end.
  • Remove(int startIndex, int count): removes count characters starting from startIndex.

Example:

string original = "Hello World!"; string removed1 = original.Remove(5); // "Hello" string removed2 = original.Remove(5, 6); // "Hello!"

Insert() Method

Inserts a string at a specified index into the current string.

Example:

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.

Normalize() Method

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.

Normalization Forms:

  • FormC: Canonical Composition
  • FormD: Canonical Decomposition
  • FormKC: Compatibility Composition
  • FormKD: Compatibility Decomposition

Example:

string accented = "e\u0301"; // 'e' + combining acute accent string normalized = accented.Normalize(NormalizationForm.FormC); bool areEqual = normalized == "\u00E9"; // true, 'é' as single character

ToCharArray() Method

Converts the string into an array of characters, enabling iteration or manipulation of individual characters.

Example:

string greeting = "Hi!"; char[] chars = greeting.ToCharArray(); foreach(char c in chars) { Console.WriteLine(c); } // Output: // H // i // !

String Interpolation and Formatting

Although not a method of String itself, string interpolation and formatting are essential for dynamic string creation.

String Interpolation

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."

String.Format()

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."

Performance Considerations

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.

Summary Table of Part 2 Methods

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()

Related Tutorials

Frequently Asked Questions for C#

C# is much easier to learn than C++. C# is a simpler, high-level-of-abstraction language, while C++ is a low-level language with a higher learning curve.

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Python and JavaScript programmers also earn high salaries, ranking #3 and #4 in compensation. 
C# is the highest-paid programming language but has less demand than Python, JavaScript, and Java.

No. Microsoft has invested substantially in ensuring that C# is the dominant language today, spending two billion dollars on marketing and attempting to convince developers to embrace this new platform, which is also based on the.NET foundation.

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.


You can’t be able to become Master of C# in 3 months since it has many concepts to learn and implement. NOTE: no one can become master in particular programming language. Everyday they introducing new concepts we need to get practice on it which practically somewhat tough.

C-Sharp is one of the most widely used languages for creating system backend.It's because of its incredible features, such as Windows server automation. Apart from that, it's fantastic because it runs codes quite quickly. It can also be used to create CLI applications and game creation.

Easy to learn and use: C# is simpler than Java due to its use of fewer keywords and usually shorter lines of code. Hence, it is easier to learn to code in C# compared to Java. Flexible Data Types: C# provides more flexibility in defining data types than Java.

Four steps of code compilation in C# include : 
  • Source code compilation in managed code.
  • Newly created code is clubbed with assembly code.
  • The Common Language Runtime (CLR) is loaded.
  • Assembly execution is done through CLR.

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.


Among other languages, C# is gaining huge popularity for developing web-based applications. Its core concepts help build an interactive environment and provide functionalities that the dynamic web platform requires. Most aspiring full-stack developers choose this versatile language.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270 and 20619) in 2003. Microsoft introduced C# along with .NET Framework and Visual Studio, both of which were closed-source. 

C# outshines Python when it comes to runtime performance. As a compiled language, C# code is converted to machine code, which can be executed more efficiently by the processor. This results in faster execution times and better performance, especially in resource-intensive tasks.

Yes, C# is used by many large organizations, start-ups and beginners alike. It takes some of the useful features of C and adds syntax to save time and effort. Although C# is based on C, you can learn it without any knowledge of C — in fact, this course is perfect for those with no coding experience at all!

C# is a very mature language that evolved significantly over the years.
The C# language is one of the top 5 most popular programming languages and .NET is the most loved software development framework in the world.
TIOBE Index predicts C# as 2023 'Language of the Year' close to overtake Java in popularity.

Generally, the C# language is not limited to the Windows operating system. In a sense, however, it is limited to Microsoft software. C# language "belongs" to Microsoft, it is developed by Microsoft and it is Microsoft that provides the runtime environment required for the operation of programs written in C#.

C# (pronounced "C sharp") is called so because the "#" symbol is often referred to as "sharp." The name was chosen by Microsoft when they developed the language. It's a play on words related to musical notation where "C#" represents the musical note C sharp.

Dennis MacAlistair Ritchie (September 9, 1941 – c. October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B language.

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.


line

Copyrights © 2024 letsupdateskills All rights reserved