How to Use Substring Method in C#
The Substring method is used to take out a part of a string based on the length of the substring and its specified starting index and returns a new string that represents the extracted substring.
The startingIndex parameter is the zero-based index where the substring should start. The length parameter is the number of characters to include in the substring, here is an example code that extracts “Hello” and “Linux” from the string “Hello Linux” using two techniques of Substring methods:
class Program
{
static void Main(string[] args)
{
string myString = "Hello Linux";
// Call Substring() method to get a substring of 'myString' starting from index 6 and 5 characters long
string mySubstring = myString.Substring(0, 5);
// Output the resulting substring
Console.WriteLine(mySubstring); // Output: Linux
// Call Substring() method to get a substring of 'myString' starting from index 6 to the end of the string
string mySubstring2 = myString.Substring(6);
// Output the resulting substring
Console.WriteLine(mySubstring2); // Output: Linux
}
}
In this example, we create a string myString containing the value “Hello Linux”. We then use the Substring method to extract the word “Linux” from the string using the starting index 0 and the length 5. We output the result to the console.
We also demonstrate the usage of the Substring method when the length parameter is omitted. In this case, the method returns all characters starting from the startingIndex (6) to the end of the string.
It is important to note that this method will throw an exception if the startingIndex parameter is less than zero or greater than or equal to the length of the string, or if the length parameter is less than zero or greater than the length of the remaining substring. It is important to check the validity of the input parameters before calling this method to avoid runtime exceptions, here is the output of the code:
Conclusion
The String.Substring() method is a valuable tool in the C# developer’s toolkit. It can be used to extract specific portions of a string for processing or display purposes, and it is easy to use and highly customizable. This guide gives the syntax for using it along with an example that demonstrates the use of this method.