C# String Substring Method

  Keywords : c# string substring, c# substring example, substring c# example, csharp substring example, c# substring from end, c# find substring in string, c# substring method example

Here we will learn substring method in c# with examples and how to use c# substring method to get a substring from given string starting from particular position with examples.

C# Substring Method

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

 

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

 

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

 

C# Substring Method Representation Diagram

 

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

C# Substring Method Syntax

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

 

public string Substring(int startIndex)

public string Substring(int startIndex, int length)

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

C# Substring Method Example

Following is the example of using Substring() method to get a substring starting from the given string in 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 Any Key to Exit..");

            Console.ReadLine();

        }

    }

}

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

 

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

 

C# String Substring Method Example Result

 

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

 

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