Paramclasses Academy - Blog

Tutorials Details

←
Post 10 of 30
→

What is C# Strings and String Methods. ? 20 Useful Methods with Examples

What is C# Strings and String Methods. ? 20 Useful Methods with Examples

October 24, 2026

Introduction

Strings are one of the most commonly used data types in C# programming. They allow developers to store and manipulate text, including names, email addresses, messages, passwords, product descriptions, and other textual information.

For example:

string name = "Rahul";
string message = "Welcome to C# Programming!";
string email = "rahul@example.com";

In C#, the string keyword is an alias for System.String. A string represents a sequence of UTF-16 code units and is a reference type.

Strings are immutable, which means that once a string object is created, its contents cannot be changed. String operations that appear to modify text generally return a new string rather than changing the original one.

In this tutorial, you will learn how to declare strings, access characters, compare text, extract substrings, replace text, split strings, format output, and use 20 essential string methods.

1. Declaring and Initializing Strings

You can declare a string variable and assign a text value using double quotation marks.

Example

string firstName = "Rahul";
string lastName = "Sharma";

Console.WriteLine(firstName);
Console.WriteLine(lastName);

Output:

Rahul
Sharma

String Concatenation

You can combine strings using the + operator.

string firstName = "Rahul";
string lastName = "Sharma";

string fullName = firstName + " " + lastName;

Console.WriteLine(fullName);

Output:

Rahul Sharma

String Interpolation

String interpolation provides a readable way to insert variables and expressions into a string using the $ prefix.

string name = "Rahul";
int age = 22;

Console.WriteLine($"My name is {name} and I am {age} years old.");

Output:

My name is Rahul and I am 22 years old.

String interpolation is generally easier to read than combining many strings with the + operator.

2. Understanding String Immutability

Strings cannot be modified in place. Methods such as Replace(), ToUpper(), and Trim() return a string containing the result.

Example

string text = "hello";

text.ToUpper();

Console.WriteLine(text);

Output:

hello

The result of ToUpper() was not assigned back to text.

Correct approach:

string text = "hello";

text = text.ToUpper();

Console.WriteLine(text);

Output:

HELLO

Alternatively, you can store the result in another variable:

string original = "hello";
string uppercase = original.ToUpper();

Console.WriteLine(original);
Console.WriteLine(uppercase);

Output:

hello
HELLO

The original string remains unchanged.

3. The Length Property

Although Length is a property rather than a method, it is one of the most useful string members.

It returns the number of UTF-16 code units in the string.

Example

string message = "Hello World";

Console.WriteLine(message.Length);

Output:

11

The space between Hello and World is included in the length.

Important: Length does not always equal the number of user-perceived characters. Some Unicode characters, including many emoji, require multiple UTF-16 code units.


4. Twenty Useful C# String Methods

Method 1: ToUpper()

The ToUpper() method returns a new string in which lowercase letters are converted to uppercase.

string text = "hello world";

Console.WriteLine(text.ToUpper());

Output:

HELLO WORLD

Use case: Displaying text in uppercase or normalizing text for presentation.

For language-independent comparisons, consider ordinal comparison methods rather than relying on case conversion alone.

Method 2: ToLower()

The ToLower() method returns a new string with letters converted to lowercase according to the current culture.

string text = "HELLO WORLD";

Console.WriteLine(text.ToLower());

Output:

hello world

Use case: Preparing text for display or performing culture-appropriate text processing.

For identifiers and other machine-oriented text, use an appropriate explicit comparison strategy.

Method 3: Trim()

The Trim() method removes leading and trailing whitespace.

string text = "   Hello C#   ";

Console.WriteLine(text.Trim());

Output:

Hello C#

It does not remove spaces between words.

Use case: Cleaning user input before validation or processing.

Method 4: TrimStart()

The TrimStart() method removes whitespace from the beginning of a string.

string text = "   Hello C#   ";

Console.WriteLine(text.TrimStart());

Output:

Hello C#   

The trailing spaces remain.

Use case: Removing unwanted leading whitespace from text.

Method 5: TrimEnd()

The TrimEnd() method removes whitespace from the end of a string.

string text = "   Hello C#   ";

Console.WriteLine(text.TrimEnd());

Output:

   Hello C#

The leading spaces remain.

Use case: Cleaning trailing spaces in user input or imported text.

Method 6: Contains()

The Contains() method checks whether a string contains a specified sequence of characters.

It returns true if the sequence is found and false otherwise.

string message = "Welcome to C# Programming";

Console.WriteLine(message.Contains("C#"));
Console.WriteLine(message.Contains("Java"));

Output:

True
False

The default string search is case-sensitive.

For an explicit case-insensitive search, you can use:

string message = "Welcome to C# Programming";

bool found = message.Contains(
    "c#",
    StringComparison.OrdinalIgnoreCase);

Console.WriteLine(found);

Output:

True

Use case: Searching for keywords or checking whether text includes a particular phrase.

Method 7: StartsWith()

The StartsWith() method checks whether a string begins with a specified value.

string website = "https://example.com";

Console.WriteLine(website.StartsWith("https"));
Console.WriteLine(website.StartsWith("ftp"));

Output:

True
False

Use case: Checking text prefixes or identifying expected input formats.

For security-sensitive URL validation, do not rely only on a string prefix. Parse the URL and validate its scheme and host.

Method 8: EndsWith()

The EndsWith() method checks whether a string ends with a specified value.

string fileName = "document.pdf";

Console.WriteLine(fileName.EndsWith(".pdf"));
Console.WriteLine(fileName.EndsWith(".jpg"));

Output:

True
False

Use case: Basic filename checks and identifying text suffixes.

A suffix check alone is not a security guarantee that a file contains the expected content.

Method 9: IndexOf()

The IndexOf() method returns the zero-based index of the first occurrence of a specified character or substring. If the value is not found, it returns -1.

string text = "Hello C# Programming";

Console.WriteLine(text.IndexOf("C#"));
Console.WriteLine(text.IndexOf("Java"));

Output:

6
-1

The substring C# begins at index 6.

Use case: Locating text, delimiters, or characters within a string.

Method 10: LastIndexOf()

The LastIndexOf() method returns the index of the last occurrence of a specified character or substring.

string text = "one two one";

Console.WriteLine(text.LastIndexOf("one"));

Output:

8

The final occurrence of one begins at index 8.

Use case: Finding the last delimiter or the final occurrence of a substring.

Method 11: Substring()

The Substring() method extracts a portion of a string using a starting index and, optionally, a length.

string text = "Hello World";

Console.WriteLine(text.Substring(0, 5));
Console.WriteLine(text.Substring(6));

Output:

Hello
World

In the first example, Substring(0, 5) starts at index 0 and extracts five UTF-16 code units. In the second example, the substring extends from index 6 to the end.

Invalid indexes or lengths can cause an ArgumentOutOfRangeException.

Use case: Extracting portions of known text formats.

For complex text processing, consider whether other APIs or parsing techniques would be more appropriate.

Method 12: Replace()

The Replace() method returns a new string in which occurrences of a specified character or substring are replaced.

string text = "I like Java";

string result = text.Replace("Java", "C#");

Console.WriteLine(result);

Output:

I like C#

The original variable text remains unchanged unless you assign the result back to it.

Use case: Replacing words, correcting text, or transforming string content.

Method 13: Split()

The Split() method divides a string into an array of substrings using one or more separators.

string fruits = "Apple,Banana,Mango,Orange";

string[] result = fruits.Split(',');

foreach (string fruit in result)
{
    Console.WriteLine(fruit);
}

Output:

Apple
Banana
Mango
Orange

Use case: Processing comma-separated values, simple delimited text, or lists.

For real CSV files, use a CSV parser because quoted fields may contain commas, quotation marks, and line breaks.

Method 14: Join()

The String.Join() method combines multiple strings or collection elements into a single string using a specified separator.

string[] fruits = { "Apple", "Banana", "Mango" };

string result = string.Join(", ", fruits);

Console.WriteLine(result);

Output:

Apple, Banana, Mango

Use case: Creating comma-separated lists, readable summaries, or formatted text.

Method 15: Remove()

The Remove() method removes a specified number of UTF-16 code units from a string, starting at a specified index.

string text = "Hello World";

Console.WriteLine(text.Remove(5));
Console.WriteLine(text.Remove(5, 6));

Output:

Hello
Hello

In the first example, everything from index 5 to the end is removed. In the second, six code units beginning at index 5 are removed.

Use case: Removing known portions of text when the position is reliable.

Method 16: Insert()

The Insert() method inserts a string at a specified zero-based index and returns a new string.

string text = "Hello World";

string result = text.Insert(6, "C# ");

Console.WriteLine(result);

Output:

Hello C# World

Use case: Inserting labels, separators, or additional text at a known position.

Method 17: PadLeft()

The PadLeft() method adds padding characters to the beginning of a string until it reaches the specified total length.

string number = "42";

Console.WriteLine(number.PadLeft(5, '0'));

Output:

00042

Use case: Aligning text or formatting identifiers with leading zeroes.

Method 18: PadRight()

The PadRight() method adds padding characters to the end of a string until it reaches the specified total length.

string name = "Rahul";

Console.WriteLine(name.PadRight(10, '.'));

Output:

Rahul.....

Use case: Creating aligned text output or simple console reports.

For production reports, consider formatted output or table-rendering libraries where appropriate.

Method 19: IsNullOrEmpty()

string.IsNullOrEmpty() is a static method that checks whether a string is null or empty ("").

string? name = "";

Console.WriteLine(string.IsNullOrEmpty(name));

name = "Rahul";

Console.WriteLine(string.IsNullOrEmpty(name));

Output:

True
False

Use case: Checking whether required text has been supplied.

This method does not consider a string containing only spaces to be empty.

Method 20: IsNullOrWhiteSpace()

string.IsNullOrWhiteSpace() checks whether a string is null, empty, or contains only whitespace characters.

string? name = "   ";

Console.WriteLine(string.IsNullOrWhiteSpace(name));

name = "Rahul";

Console.WriteLine(string.IsNullOrWhiteSpace(name));

Output:

True
False

Use case: Validating fields where whitespace alone should not count as meaningful input.

For many user-input checks, IsNullOrWhiteSpace() is more useful than IsNullOrEmpty().


5. Quick Reference: 20 String Methods

No. Method Purpose
1 ToUpper() Converts text to uppercase
2 ToLower() Converts text to lowercase
3 Trim() Removes leading and trailing whitespace
4 TrimStart() Removes leading whitespace
5 TrimEnd() Removes trailing whitespace
6 Contains() Checks whether a substring exists
7 StartsWith() Checks the beginning of a string
8 EndsWith() Checks the end of a string
9 IndexOf() Finds the first occurrence
10 LastIndexOf() Finds the last occurrence
11 Substring() Extracts a portion of a string
12 Replace() Replaces matching text
13 Split() Divides text into substrings
14 String.Join() Combines strings with a separator
15 Remove() Removes text by position
16 Insert() Inserts text at a position
17 PadLeft() Adds padding to the left
18 PadRight() Adds padding to the right
19 string.IsNullOrEmpty() Checks for null or empty text
20 string.IsNullOrWhiteSpace() Checks for null, empty, or whitespace-only text

6. String Comparison in C#

Comparing strings is common when checking usernames, commands, product codes, or other text values.

Using Equals()

string first = "Hello";
string second = "Hello";

Console.WriteLine(first.Equals(second));

Output:

True

By default, this comparison is case-sensitive.

string first = "hello";
string second = "HELLO";

Console.WriteLine(first.Equals(second));

Output:

False

Case-Insensitive Comparison

For case-insensitive comparisons of identifiers or machine-oriented text, use an explicit comparison mode.

string first = "hello";
string second = "HELLO";

bool result = string.Equals(
    first,
    second,
    StringComparison.OrdinalIgnoreCase);

Console.WriteLine(result);

Output:

True

Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for many non-linguistic comparisons. For language-sensitive sorting or searching, use culture-aware comparison options.

Important: Passwords should not be normalized or converted to uppercase or lowercase unless the authentication system's explicit design requires it. Password comparison should follow the system's secure password-verification process.

7. String Formatting in C#

C# offers several ways to create formatted strings.

String Interpolation

string product = "Laptop";
double price = 54999.50;

Console.WriteLine($"Product: {product}, Price: {price:F2}");

Output:

Product: Laptop, Price: 54999.50

String.Format()

string name = "Rahul";
int age = 22;

string result = string.Format(
    "Name: {0}, Age: {1}",
    name,
    age);

Console.WriteLine(result);

Output:

Name: Rahul, Age: 22

Verbatim Strings

A verbatim string uses the @ prefix and treats backslashes as ordinary characters.

string path = @"C:\Users\Rahul\Documents";

Console.WriteLine(path);

Output:

C:\Users\Rahul\Documents

Verbatim strings are useful for Windows-style paths and text containing many backslashes.

Raw String Literals

Modern C# supports raw string literals, which use three or more quotation marks.

string json = """
{
    "name": "Rahul",
    "language": "C#"
}
""";

Console.WriteLine(json);

Raw string literals are convenient for multiline text, JSON examples, and embedded content.

8. Practical Project: User Input Validator

Let's combine several string methods to build a simple console program that validates a user's name and email format.

The example demonstrates whitespace handling, basic email-format checks, and string comparison.

Console.Write("Enter your name: ");
string? nameInput = Console.ReadLine();

string name = nameInput?.Trim() ?? string.Empty;

if (string.IsNullOrWhiteSpace(name))
{
    Console.WriteLine("Name is required.");
}
else
{
    Console.WriteLine($"Welcome, {name}!");

    Console.Write("Enter your email: ");
    string? emailInput = Console.ReadLine();

    string email = emailInput?.Trim() ?? string.Empty;

    bool looksLikeEmail =
        !string.IsNullOrWhiteSpace(email) &&
        email.Contains('@') &&
        email.Contains('.') &&
        email.IndexOf('@') > 0 &&
        email.IndexOf('@') < email.LastIndexOf('.');

    if (looksLikeEmail)
    {
        Console.WriteLine("The email has a basic acceptable format.");
    }
    else
    {
        Console.WriteLine("Please enter an email in a basic valid format.");
    }
}

Example output:

Enter your name:   Rahul
Welcome, Rahul!
Enter your email: rahul@example.com
The email has a basic acceptable format.

How the Program Works

  • Trim() removes leading and trailing whitespace.

  • string.IsNullOrWhiteSpace() checks whether the name is missing or contains only whitespace.

  • Contains() checks for the presence of @ and ..

  • IndexOf() locates the first occurrence of @.

  • LastIndexOf() locates the final period.

  • String interpolation displays the resulting message.

Important limitation: This is only a basic demonstration, not a complete email validator. Real applications should use an appropriate validation strategy and verify addresses through the relevant business process when necessary.

9. Common String Handling Mistakes

Mistake 1: Forgetting String Immutability

Calling ToUpper() or Replace() does not modify the original string.

string text = "hello";

text.ToUpper();

Console.WriteLine(text);

Output:

hello

Correct approach:

text = text.ToUpper();

Mistake 2: Confusing Case-Sensitive Searches

string text = "Hello World";

Console.WriteLine(text.Contains("hello"));

Output:

False

The default search is case-sensitive.

Mistake 3: Ignoring Null Values

A string variable can contain null. Calling an instance method on a null reference can throw a NullReferenceException.

Use null checks, nullable reference types, or appropriate null-safe expressions.

Mistake 4: Using Substring Without Checking Bounds

An invalid starting index or length can cause an ArgumentOutOfRangeException.

Validate the input length or use suitable parsing techniques before extracting text.

Mistake 5: Treating Split() as a Complete CSV Parser

A simple Split(',') operation cannot correctly handle all CSV features, such as quoted commas and multiline fields. Use a dedicated CSV parser for actual CSV data.

Mistake 6: Repeated String Concatenation in Large Loops

Because strings are immutable, repeatedly concatenating strings in large loops can create unnecessary allocations.

For intensive repeated text building, consider StringBuilder.

10. String vs StringBuilder

string is suitable for ordinary text values and operations that create a limited number of new strings. StringBuilder is designed for scenarios involving repeated modifications to a growing text buffer.

Example Using StringBuilder

using System.Text;

StringBuilder builder = new StringBuilder();

builder.Append("Hello");
builder.Append(' ');
builder.Append("C#");
builder.Append(" Programming");

Console.WriteLine(builder.ToString());

Output:

Hello C# Programming

Use StringBuilder when repeatedly appending or modifying text, especially inside large loops. For simple string operations, ordinary string interpolation and concatenation are often sufficient.

11. Best Practices for C# String Handling

  • Use descriptive variable names for text values.

  • Prefer string interpolation for readable formatted output.

  • Use Trim() when leading or trailing whitespace should be removed.

  • Choose IsNullOrWhiteSpace() when whitespace-only input should be rejected.

  • Use explicit comparison rules for identifiers and machine-oriented text.

  • Check string indexes and lengths before extracting substrings.

  • Use a proper parser for structured formats such as CSV, JSON, and URLs.

  • Avoid assuming that Length equals the number of visible characters.

  • Use StringBuilder when repeated text modification creates a performance concern.

  • Be careful with sensitive information such as passwords, tokens, and private data.

12. Practice Exercises

Exercise 1: Text Analyzer

Write a program that accepts a sentence and displays:

  1. The sentence length.

  2. The sentence in uppercase.

  3. The sentence in lowercase.

  4. Whether it contains the word C#.

  5. The position of the first occurrence of C#.

Exercise 2: Name Formatter

Ask the user to enter their first and last name. Remove unnecessary leading and trailing whitespace and display the formatted full name.

Exercise 3: Word Splitter

Accept a comma-separated list of fruit names, split the text, trim each item, and print each fruit on a separate line.

Exercise 4: Text Replacement

Ask the user to enter a sentence and replace every occurrence of a selected word with another word.

Exercise 5: Palindrome Checker

Write a program to check whether a word reads the same forward and backward, such as level or madam.

Bonus challenge: Extend the palindrome checker to ignore letter case and spaces. Decide how punctuation and Unicode characters should be handled.

13. Frequently Asked Questions

Q1. What is a string in C#?

A string is a reference type used to represent text. The string keyword is an alias for System.String.

Q2. Are strings mutable in C#?

No. Strings are immutable. Operations that appear to change a string return a new string.

Q3. What is the difference between Length and Count?

Length is a property of a string that returns the number of UTF-16 code units. Count is not a built-in string property, although LINQ can provide a Count() extension method.

Q4. What is the difference between Trim() and Replace()?

Trim() removes leading and trailing whitespace by default. Replace() replaces occurrences of specified text or characters.

Q5. What does IndexOf() return if text is not found?

It returns -1 when the specified value is not found.

Q6. What is the difference between Split() and Join()?

Split() divides a string into multiple substrings. String.Join() combines multiple strings into one string with a chosen separator.

Q7. When should I use StringBuilder?

Use StringBuilder when building or modifying text repeatedly, particularly when a large amount of text is appended in a loop.

Q8. Are strings case-sensitive in C#?

String content comparisons and searches are often case-sensitive by default. The exact behavior depends on the method and comparison options used.

14. Quick Knowledge Check

Question 1: Which method removes leading and trailing whitespace?

A. Replace()

B. Trim()

C. Split()

D. Insert()

Question 2: Which method returns -1 when a substring is not found?

A. Contains()

B. Replace()

C. IndexOf()

D. Join()

Question 3: Which method divides a string into an array of substrings?

A. Split()

B. Join()

C. PadLeft()

D. Remove()

Question 4: Why might you use StringBuilder?

A. To change an array's length

B. To repeatedly build or modify text efficiently

C. To validate every email address

D. To convert strings into integers automatically

Answers: 1 — B, 2 — C, 3 — A, 4 — B.

Conclusion

String handling is an essential part of C# development. Understanding string immutability, comparison, searching, extraction, replacement, formatting, and validation will help you write cleaner and more reliable applications.

The 20 methods covered in this tutorial provide a strong foundation for processing names, messages, product descriptions, user input, and other text-based information.

Practice these examples in a C# console application and experiment with different inputs. As you progress, you will use string operations in web development, database applications, file processing, and many other areas of .NET programming.

←
Post 10 of 30
→