Home » .Net

How to get substring from a string in C#?

Here, we will learn how to get substring from a given string using C# program? To get substring from a string there is a method of string class String.SubString() which takes starting index and total number of characters (length) to get.

Given a string and we have to get the substring of N characters.

For 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()

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

Syntax:

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

Here,
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.

Consider the program:

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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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.