c sharp

How to Use Substring Method in C#

The String.Substring() method is a powerful tool in C# that allows developers to extract a specified portion of a string. It takes a starting index and a length parameter and returns the specified substring. This guide will explain what is substring method and how to use this method in C#.

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.

string.Substring(<starting-index>, <length>);

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:

using System;

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.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.