C# - Print All Possible Substrings of a String

Given a string, we have to print all possible substrings of a string using C# program.
Submitted by Nidhi, on October 12, 2020 [Last updated : March 21, 2023]

Here, we will find the all possible substrings and then print them on the console screen.

C# program to print all possible substrings of a string

The source code to print the list of all possible substrings is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to print the list of all 
//possible substrings of a specified string.

using System;

class Demo
{
    static void GetSubStrings(string str)
    {
        int j=0;
        int i=0;

        Console.WriteLine("Possible sub-strings are :");
        for (i = 1; i <= str.Length; i++)
        {
            for (j = 0; j <= str.Length - i; j++)
            {   
                Console.WriteLine(str.Substring(j, i));
            }
        }
    }
    public static void Main()
    {
        string str;

        Console.Write("Enter the String : ");
        str = Console.ReadLine();

        GetSubStrings(str);
    }
}

Output

Enter the String : IncludeHelp
Possible sub-strings are :
I
n
c
l
u
d
e
H
e
l
p
In
nc
cl
lu
ud
de
eH
He
el
lp
Inc
ncl
clu
lud
ude
deH
eHe
Hel
elp
Incl
nclu
clud
lude
udeH
deHe
eHel
Help
Inclu
nclud
clude
ludeH
udeHe
deHel
eHelp
Includ
nclude
cludeH
ludeHe
udeHel
deHelp
Include
ncludeH
cludeHe
ludeHel
udeHelp
IncludeH
ncludeHe
cludeHel
ludeHelp
IncludeHe
ncludeHel
cludeHelp
IncludeHel
ncludeHelp
IncludeHelp
Press any key to continue . . .

Explanation

Here, we created a class Demo that contains two static methods GetSubstrings() and Main().

The GetSubstrings() method is used to find all possible substring based on a given string and then print them on the console screen.

The Main() method is the entry point for the program execution. Here we read a string and then find possible substrings using the GetSubstrings() method.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





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