C# String Substring Method

In c#, the Substring method is useful to get a substring from the given string. The substring starts from the specified character position and continues to the end of the string.

 

If we want to get the particular length of the substring, then we can specify the length of the substring to return from the given string.

 

Following is the pictorial representation of using the Substring() method to get a substring from the given string in the c# programming language.

 

C# Substring Method Representation Diagram

 

If you observe the above diagram, we are getting a substring starting from position 5 using the Substring method.

C# Substring Method Syntax

Following is the syntax of defining a Substring method to get a substring from the given string in the c# programming language.

 

public string Substring(int startIndex)
public string Substring(int startIndex, int length)

If you observe the syntax, the Substring method will return a substring starting from the specified position.

C# Substring Method Example

Following is the example of using the Substring() method to get a substring starting from the given string in the c# programming language.

 

using System;

namespace Tutlane
{
    class Program
    {
       static void Main(string[] args)
       {
          string msg = "Welcome to Tutlane";
          Console.WriteLine("SubString: {0}", msg.Substring(5));
          Console.WriteLine("Substring with Length: {0}", msg.Substring(3, 7));
          Console.WriteLine("\nPress Enter Key to Exit..");
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used a Substring() method to get a substring starting from position 5 till the end of the defined string and another substring starting from position 3, and the length of the substring should be 7 characters.

 

When you execute the above c# program, you will get the result as shown below.

 

C# String Substring Method Example Result

 

If you observe the above result, the Substring() method has returned the required substrings with or without a specified length based on our requirements.

 

This is how you can use the Substring() method to get required substrings from the given string starting from the defined position in the c# programming language.