C# - Get Substring from a String

Given a string and we have to get the substring of N characters.
[Last updated : March 20, 2023]

To get a substring from the given string, we use String.Substring() method.

Example

Input string is "India is great country" and we want to extract the substring (5 characters ) from 9th index, which will be "great".

String.Substring()

The String.Substring() method returns the given number of characters (length) from given starting position (index).

Syntax

String String.Substring(int index, int length );

Parameter(s)

  • index – is the starting indexing from where you want to extract the substring (indexing starts from 0).
  • length – is the total number of characters to be extracted.

Return Type

String – method will return the length characters from index (substring), which will be the result.

C# program to get substring from a string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      String str1;
      String str2;

      Console.Write("Enter string : ");
      str1 = Console.ReadLine();

      str2 = str1.Substring(9, 5);

      Console.WriteLine("Sub string is: " + str2);
    }
  }

}

Output

Enter string : India is great country.
Sub string is: great

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.