C# string methods cheat sheet — Contains, Split, Replace, Trim, and more

C# strings are immutable — every method that appears to modify a string actually returns a new one. The original is never changed.

This page covers the methods that appear in day-to-day C# code. For formatting numbers and dates inside strings, see the string.Format guide.

Contains, StartsWith, EndsWith

C# Example Code
string sentence = "The quick brown fox";

Console.WriteLine(sentence.Contains("brown"));        // True
Console.WriteLine(sentence.StartsWith("The"));        // True
Console.WriteLine(sentence.EndsWith("cat"));          // False

// Case-insensitive comparison
Console.WriteLine(sentence.Contains("BROWN",
    StringComparison.OrdinalIgnoreCase));             // True

// Check for any of several substrings
bool hasAnimal = sentence.Contains("fox") || sentence.Contains("dog");
Console.WriteLine(hasAnimal);                         // True

Split — Break a String into Parts

C# Example Code
string csv = "Alice,Bob,Charlie,Diana";

// Split on a single character
string[] names = csv.Split(',');
foreach (string name in names)
    Console.WriteLine(name);
// Alice
// Bob
// Charlie
// Diana

// Split on a string delimiter
string log = "ERROR|404|Page not found";
string[] parts = log.Split('|');
Console.WriteLine(parts[0]); // ERROR
Console.WriteLine(parts[1]); // 404
Console.WriteLine(parts[2]); // Page not found

// Split on multiple delimiters and remove empty entries
string messy = "one,,two, ,three";
string[] clean = messy.Split(
    new[] { ',', ' ' },
    StringSplitOptions.RemoveEmptyEntries
);
// ["one", "two", "three"]

Replace — Substitute Text

C# Example Code
string text = "Hello, World! Hello, C#!";

// Replace a substring
string result = text.Replace("Hello", "Hi");
Console.WriteLine(result);
// Hi, World! Hi, C#!

// Replace a single character
string path = @"C:\Users\Alice\Documents";
string webPath = path.Replace('\\', '/');
Console.WriteLine(webPath);
// C:/Users/Alice/Documents

// Remove a substring by replacing with empty string
string noSpaces = "remove all spaces".Replace(" ", "");
Console.WriteLine(noSpaces); // removeallspaces

Trim, TrimStart, TrimEnd

C# Example Code
string raw = "   hello world   ";

Console.WriteLine(raw.Trim());       // "hello world"
Console.WriteLine(raw.TrimStart());  // "hello world   "
Console.WriteLine(raw.TrimEnd());    // "   hello world"

// Trim specific characters
string url = "///path/to/resource///";
Console.WriteLine(url.Trim('/'));    // "path/to/resource"

// Common use case: clean user input before validation
string userInput = "  alice@example.com  ";
string email = userInput.Trim().ToLower();
Console.WriteLine(email); // alice@example.com

ToUpper, ToLower

C# Example Code
string name = "Alice Smith";

Console.WriteLine(name.ToUpper()); // ALICE SMITH
Console.WriteLine(name.ToLower()); // alice smith

// Culture-aware upper/lower (important for Turkish 'i'→'İ')
string turkish = "istanbul";
Console.WriteLine(turkish.ToUpper());   // ISTANBUL (invariant)
Console.WriteLine(turkish.ToUpper(
    System.Globalization.CultureInfo.GetCultureInfo("tr-TR"))); // İSTANBUL

Substring and IndexOf

C# Example Code
string text = "Hello, World!";

// Substring(startIndex, length)
Console.WriteLine(text.Substring(7, 5));  // World

// IndexOf returns -1 when not found
int idx = text.IndexOf("World");
if (idx >= 0)
    Console.WriteLine($"Found at index {idx}"); // Found at index 7

// LastIndexOf — search from the end
string path = "/home/user/documents/report.pdf";
int lastSlash = path.LastIndexOf('/');
string fileName = path.Substring(lastSlash + 1);
Console.WriteLine(fileName); // report.pdf

// Modern alternative: Range syntax (C# 8+)
string first5 = text[..5];    // "Hello"
string last6  = text[^6..];   // "World!"

PadLeft and PadRight

C# Example Code
// Right-align numbers in a fixed-width column
int[] numbers = { 1, 42, 999, 10_000 };
foreach (int n in numbers)
    Console.WriteLine(n.ToString().PadLeft(8));

// Output (right-aligned):
//        1
//       42
//      999
//    10000

// Left-align strings
string[] labels = { "Name", "Department", "ID" };
foreach (string label in labels)
    Console.WriteLine(label.PadRight(15) + "|");

// Output:
// Name           |
// Department     |
// ID             |

// Zero-pad a number
string code = "42".PadLeft(6, '0');
Console.WriteLine(code); // 000042

String.IsNullOrEmpty and IsNullOrWhiteSpace

C# Example Code
string? a = null;
string  b = "";
string  c = "   ";
string  d = "hello";

Console.WriteLine(string.IsNullOrEmpty(a));          // True
Console.WriteLine(string.IsNullOrEmpty(b));          // True
Console.WriteLine(string.IsNullOrEmpty(c));          // False ← whitespace is not empty
Console.WriteLine(string.IsNullOrWhiteSpace(c));     // True  ← catches whitespace-only
Console.WriteLine(string.IsNullOrWhiteSpace(d));     // False

String.Join — Combine a Collection into a String

C# Example Code
string[] fruits = { "apple", "banana", "cherry" };

// Join with a separator
string joined = string.Join(", ", fruits);
Console.WriteLine(joined); // apple, banana, cherry

// Join integers
int[] nums = { 1, 2, 3, 4, 5 };
Console.WriteLine(string.Join(" + ", nums)); // 1 + 2 + 3 + 4 + 5

// Join with newline
string multiLine = string.Join(Environment.NewLine, fruits);

String.Concat and + Operator

C# Example Code
string first = "Hello";
string last  = "World";

// These are equivalent for 2–3 strings
string s1 = first + ", " + last + "!";
string s2 = string.Concat(first, ", ", last, "!");

Console.WriteLine(s1); // Hello, World!
Console.WriteLine(s2); // Hello, World!

// For many concatenations in a loop, prefer StringBuilder
// For a fixed set of values, + or string.Concat is fine

Quick Reference

MethodWhat it does
Contains(s)Returns true if the string contains s
StartsWith(s)Returns true if string starts with s
EndsWith(s)Returns true if string ends with s
IndexOf(s)First index of s, or -1 if not found
LastIndexOf(s)Last index of s, or -1 if not found
Replace(old, new)Returns a new string with all occurrences replaced
Split(char)Splits into an array on the given delimiter
Trim()Removes leading and trailing whitespace
TrimStart()Removes leading whitespace
TrimEnd()Removes trailing whitespace
ToUpper()Converts all characters to uppercase
ToLower()Converts all characters to lowercase
Substring(i, n)Returns n characters starting at index i
PadLeft(n)Right-aligns in a field of width n
PadRight(n)Left-aligns in a field of width n
IsNullOrEmpty(s)true if null or ""
IsNullOrWhiteSpace(s)true if null, "", or whitespace only