How to Use Substring in C#: Syntax and Examples
In C#, use the
Substring method on a string to extract a part of it by specifying the start index and optionally the length. For example, myString.Substring(2, 4) returns 4 characters starting from index 2.Syntax
The Substring method extracts a portion of a string starting at a specified index. It has two common forms:
string.Substring(int startIndex): extracts fromstartIndexto the end of the string.string.Substring(int startIndex, int length): extractslengthcharacters starting atstartIndex.
Indexes start at 0, meaning the first character is at index 0.
csharp
string Substring(int startIndex); string Substring(int startIndex, int length);
Example
This example shows how to extract parts of a string using both forms of Substring. It prints the extracted parts to the console.
csharp
using System; class Program { static void Main() { string text = "Hello, World!"; // Extract from index 7 to end string part1 = text.Substring(7); // Extract 6 characters starting at index 7 string part1Corrected = text.Substring(7, 6); // Extract 5 characters starting at index 0 string part2 = text.Substring(0, 5); Console.WriteLine(part1); // Output: World! Console.WriteLine(part1Corrected); // Output: World! Console.WriteLine(part2); // Output: Hello } }
Output
World!
World!
Hello
Common Pitfalls
Common mistakes when using Substring include:
- Using a
startIndexthat is negative or greater than the string length, which causes anArgumentOutOfRangeException. - Specifying a
lengththat extends beyond the string's end, also causing an exception. - Forgetting that string indexes start at 0, leading to off-by-one errors.
Always check string length before calling Substring to avoid errors.
csharp
string text = "Example"; // Wrong: startIndex too large // string wrong = text.Substring(10); // Throws ArgumentOutOfRangeException // Correct: check length first if (text.Length > 3) { string right = text.Substring(3); Console.WriteLine(right); // Output: mple }
Output
mple
Quick Reference
| Method | Description | Example |
|---|---|---|
| Substring(int startIndex) | Extracts substring from startIndex to end | "Hello".Substring(2) → "llo" |
| Substring(int startIndex, int length) | Extracts substring of length starting at startIndex | "Hello".Substring(1, 3) → "ell" |
Key Takeaways
Use Substring(startIndex) to get part of a string from startIndex to the end.
Use Substring(startIndex, length) to get a specific length substring starting at startIndex.
String indexes start at 0; the first character is at index 0.
Avoid ArgumentOutOfRangeException by ensuring startIndex and length are within string bounds.
Always check string length before calling Substring to prevent errors.