C# String Substring() Method
The Substring()
method in C# is used to extract a substring from a string. It returns a new string that consists of a specified portion of the original string.
The syntax of the Substring()
method is as follows:
string substring = string.Substring(startIndex);Source:www.theitroad.com
or
string substring = string.Substring(startIndex, length);
Here, startIndex
is the zero-based starting index of the substring in the original string, and length
is the number of characters to include in the substring. If length
is not specified, the method returns all characters from the starting index to the end of the string.
For example, to extract a substring from a string starting at index 3, you can use the following code:
string text = "Hello World"; string substring = text.Substring(3); Console.WriteLine(substring); // Output: "lo World"
In this example, the Substring()
method is used to extract a substring starting at index 3 of the string "Hello World". The resulting substring "lo World" is assigned to the substring
variable, which is then printed to the console using the WriteLine()
method.
You can also use the Substring()
method to extract a substring of a specified length. For example, to extract a substring of length 5 starting at index 3, you can use the following code:
string text = "Hello World"; string substring = text.Substring(3, 5); Console.WriteLine(substring); // Output: "lo Wo"
In this example, the Substring()
method is used to extract a substring of length 5 starting at index 3 of the string "Hello World". The resulting substring "lo Wo" is assigned to the substring
variable, which is then printed to the console using the WriteLine()
method.