C# `String.Substring()`: Extracting Substrings from Strings
Learn how to efficiently extract substrings from strings in C# using the `String.Substring()` method. This tutorial explains its different versions, demonstrates its usage with code examples, and highlights its applications in various string manipulation and text processing tasks.
Understanding and Using C#'s `String.Substring()` Method
Introduction
The `Substring()` method in C# is used to extract a portion (a substring) of a string. It's a fundamental string manipulation function used in many programming tasks.
Method Signatures
The `Substring()` method has two commonly used versions:
Method Signatures
public string Substring(int startIndex);
public string Substring(int startIndex, int length);
Parameters
startIndex
: An integer representing the starting position (zero-based index) of the substring within the original string. The first character is at index 0.length
(in the second version): An integer specifying the number of characters to include in the substring. If omitted (first version), the substring continues to the end of the original string.
Return Value
Both versions return a new string that is a copy of the extracted substring.
Example: Extracting Substrings
This example shows how to use both versions of `Substring()`.
Example Program
using System;
public class StringExample {
public static void Main(string[] args) {
string s1 = "Hello C Sharp";
string s2 = s1.Substring(6); //Start at index 6, go to end
Console.WriteLine($"Substring 1: {s2}"); // Output: C Sharp
string s3 = s1.Substring(0, 5); //Start at 0, take 5 characters
Console.WriteLine($"Substring 2: {s3}"); // Output: Hello
}
}
Example Output
Substring 1: C Sharp
Substring 2: Hello
Explanation
In the example, s2
extracts the substring starting at index 6 (the "C" in "Hello C Sharp"), and s3
extracts the first 5 characters ( "Hello").
Important Note: Index Out Of Range
Be cautious! Providing an invalid startIndex
or length
will throw an `ArgumentOutOfRangeException`.
Conclusion
The `Substring()` method is a fundamental string utility. Understanding its usage and potential exceptions is essential for writing robust and error-free C# code.