How to get a substring from a string in C#
Overview
You can use the Substring() method to get a substring in C#.
The Substring() method takes the index position to start the retrieval of the substring as a parameter. Substring() can also take an optional parameter, which is the length of strings to return.
Syntax
public string Substring(int startIndex)
public string Substring(int startIndex, int length)
Parameters
-
startIndex: an integer value that represents the index position the substring should start from. -
length(optional): specifies the end of the substring.
Return value
The method returns a substring of a particular string.
Example
In the example below, we create some strings and use an index value to specify where the retrieval of the substrings should start from to get their substrings.
// create classclass SubStringGetter{// main methodstatic void Main(){// create stringsstring str1 = "Edpresso";string str2 = "Theodore";string str3 = "Programming";// get some substringsstring a = str1.Substring(2);string b = str2.Substring(5);string c = str3.Substring(3);// print out substringsSystem.Console.WriteLine(a);System.Console.WriteLine(b);System.Console.WriteLine(c);}}
In the code above, we use Substring() in line 13 to get the substring of Edpresso and start it from character p, which is index 2. The same pattern goes for Theodore and Programming.
Now, let’s specify the end of the substring. So far, we haven’t specified the length of the substring. Let’s do this in the example below by specifying the optional length parameter.
// create classclass SubStringGetter{// main methodstatic void Main(){// create stringsstring str1 = "Edpresso";string str2 = "Theodore";string str3 = "Programming";// get some substringsstring a = str1.Substring(2, 2);string b = str2.Substring(5, 1);string c = str3.Substring(3, 5);// print out substringsSystem.Console.WriteLine(a);System.Console.WriteLine(b);System.Console.WriteLine(c);}}
In the code above, we specify the length of our substrings.