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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.