C# String Methods
Strings in C# come with a powerful set of built-in methods. These methods let you search, modify, split, and check text without writing any complicated logic yourself. This topic covers the most useful string methods with clear examples.
Strings Are Objects
In C#, a string is not just a sequence of characters — it is a full object of the System.String class. That means every string variable automatically has access to dozens of built-in methods.
┌──────────────────────────────────────────────────────────────┐ │ STRING AS AN OBJECT │ ├──────────────────────────────────────────────────────────────┤ │ │ │ string name = "Hello World"; │ │ │ │ │ └──── Has access to: Length, ToUpper(), Split(), │ │ Replace(), Contains(), IndexOf(), Trim()... │ │ and many more built-in methods │ │ │ └──────────────────────────────────────────────────────────────┘
Length Property
Length gives you the total number of characters in a string, including spaces.
string city = "New York"; Console.WriteLine(city.Length); // Output: 8 // Diagram: // N e w Y o r k // 0 1 2 3 4 5 6 7 ← positions (index) // total = 8 characters
ToUpper() and ToLower()
These methods convert all characters to uppercase or lowercase. The original string stays unchanged — a new string is returned.
string name = "Alice"; Console.WriteLine(name.ToUpper()); // ALICE Console.WriteLine(name.ToLower()); // alice Console.WriteLine(name); // Alice (unchanged)
Immutability Diagram
┌────────────────────────────────────────────────────┐ │ string name = "Alice" │ │ │ │ │ name.ToUpper() │ │ │ │ │ ▼ │ │ NEW string "ALICE" is created and returned │ │ "Alice" still exists in memory (unchanged) │ └────────────────────────────────────────────────────┘
Trim(), TrimStart(), TrimEnd()
These methods remove extra spaces (whitespace) from a string. Very useful when processing user input.
string input = " hello "; Console.WriteLine(input.Trim()); // "hello" Console.WriteLine(input.TrimStart()); // "hello " Console.WriteLine(input.TrimEnd()); // " hello"
// Before Trim: // [ ] [h] [e] [l] [l] [o] [ ] // // After Trim(): // [h] [e] [l] [l] [o]
Contains()
Contains() checks whether a string includes a specific word or character sequence. It returns true or false.
string sentence = "C# is a powerful language";
Console.WriteLine(sentence.Contains("powerful")); // True
Console.WriteLine(sentence.Contains("Java")); // False
StartsWith() and EndsWith()
These check whether a string begins or ends with a specific piece of text.
string filename = "report2024.pdf";
Console.WriteLine(filename.StartsWith("report")); // True
Console.WriteLine(filename.EndsWith(".pdf")); // True
Console.WriteLine(filename.EndsWith(".docx")); // False
IndexOf() and LastIndexOf()
IndexOf() finds the position of the first occurrence of a character or substring. It returns -1 if not found.
string text = "banana";
Console.WriteLine(text.IndexOf('a')); // 1
Console.WriteLine(text.LastIndexOf('a')); // 5
// Position diagram:
// b a n a n a
// 0 1 2 3 4 5
// ↑ ↑
// first 'a' last 'a'
Substring()
Substring() extracts part of a string. You provide a starting position and optionally a length.
string full = "Hello, World!"; // Substring(startIndex) Console.WriteLine(full.Substring(7)); // World! // Substring(startIndex, length) Console.WriteLine(full.Substring(0, 5)); // Hello // Diagram: // H e l l o , W o r l d ! // 0 1 2 3 4 5 6 7 8 9 10 11 12 // ↑ // Substring(7) starts here
Replace()
Replace() swaps every occurrence of one string with another. It returns the modified string.
string msg = "I like cats. Cats are great.";
string updated = msg.Replace("cats", "dogs").Replace("Cats", "Dogs");
Console.WriteLine(updated);
// Output: I like dogs. Dogs are great.
Split()
Split() breaks a string into an array of smaller strings based on a separator character.
string fruits = "apple,mango,banana,grape";
string[] list = fruits.Split(',');
// Result array:
// list[0] = "apple"
// list[1] = "mango"
// list[2] = "banana"
// list[3] = "grape"
foreach (string fruit in list)
{
Console.WriteLine(fruit);
}
Split Diagram
"apple,mango,banana,grape" │ │ │ │ Split on ',' │ │ │ │ ▼ ▼ ▼ ▼ [apple] [mango] [banana] [grape]
Join()
Join() is the opposite of Split(). It combines an array of strings into one string using a separator.
string[] words = { "C#", "is", "fun" };
string sentence = string.Join(" ", words);
Console.WriteLine(sentence); // C# is fun
String.IsNullOrEmpty() and IsNullOrWhiteSpace()
These static methods check if a string is empty or contains only spaces. Use them to validate user input safely.
string a = ""; string b = " "; string c = "Hello"; Console.WriteLine(string.IsNullOrEmpty(a)); // True Console.WriteLine(string.IsNullOrEmpty(b)); // False (has spaces) Console.WriteLine(string.IsNullOrWhiteSpace(b)); // True Console.WriteLine(string.IsNullOrWhiteSpace(c)); // False
Equals() and Compare()
Equals() compares two strings for equality. By default it is case-sensitive, but you can specify otherwise.
string s1 = "hello"; string s2 = "HELLO"; Console.WriteLine(s1.Equals(s2)); // False Console.WriteLine(s1.Equals(s2, StringComparison.OrdinalIgnoreCase)); // True
String Methods Quick Reference
┌───────────────────────────┬────────────────────────────────────┐ │ Method │ What It Does │ ├───────────────────────────┼────────────────────────────────────┤ │ Length │ Count of characters │ │ ToUpper() / ToLower() │ Change case │ │ Trim() │ Remove leading/trailing spaces │ │ Contains(str) │ Check if substring exists │ │ StartsWith() / EndsWith() │ Check prefix/suffix │ │ IndexOf(ch) │ Find position of character │ │ Substring(start, len) │ Extract part of string │ │ Replace(old, new) │ Swap text │ │ Split(char) │ Break into array │ │ Join(sep, array) │ Combine array to string │ │ IsNullOrEmpty() │ Check for null or "" │ │ IsNullOrWhiteSpace() │ Check for null, "", or spaces │ │ Equals(str, comparison) │ Compare two strings │ └───────────────────────────┴────────────────────────────────────┘
String methods eliminate repetitive code. Instead of writing loops to find characters or count spaces, you call a single method that does the job instantly. Mastering these methods makes your programs shorter, cleaner, and much easier to read.
