C# – Different Ways to Find All Substrings in a String
Last Updated :
21 Oct, 2021
Given a string as an input we need to find all the substrings present in the given string.
Example:
Input:
geeks
Output:
g
e
e
k
s
ge
ee
ek
ks
gee
eek
eks
geek
eeks
geeks
Input:
ab
Output:
a
b
ab
Method 1: Using Substring() method
We can find all the substrings from the given string using the Substring() method. This method returns a substring from the current string. It contains two parameters where the first parameter represents the starting position of the substring which has to be retrieved and the second parameter will represent the length of the substring. Here if the first parameter is equal to the length of the string then this method will return nothing.
Syntax:
str.Substring(strindex, strlen)
where strindex is the starting index of the substring and strlen is the length of the substring.
Approach
To display
- Read the string from the user.
- Write the find_substrings() function to get substrings.
- In find_substrings() function call Substring() method to get the substrings.
for(i = 1; i <= input_string.Length; i++)
{
for (j = 0; j <= input_string.Length - i; j++)
{
// Use Substring function
Console.WriteLine(input_string.Substring(j, i));
}
}
- Now show the retrieved substrings.
Example:
C#
using System;
class GFG{
static void find_substrings( string input_string)
{
int j = 0;
int i = 0;
for (i = 1; i <= input_string.Length; i++)
{
for (j = 0; j <= input_string.Length - i; j++)
{
Console.WriteLine(input_string.Substring(j, i));
}
}
}
public static void Main()
{
string input_string;
Console.Write( "Enter String : " );
Console.Write( "\n" );
input_string = Console.ReadLine();
find_substrings(input_string);
}
}
|
Output:
Enter String :
GFG
G
F
G
GF
FG
GFG
Method 2: Using for loop
We can also find substring from the given string using nested for loop. Here the outer for loop is used to select starting character, mid for loop is used to considers all characters on the right of the selected starting character as the ending character of the substring, and the inner for loop is used to print characters from the starting to the ending point.
Example:
C#
using System;
class GFG{
static void find_Substring( string inputstr, int n)
{
for ( int l = 1; l <= n; l++)
{
for ( int i = 0; i <= n - l; i++)
{
int q = i + l - 1;
for ( int j = i; j <= q; j++)
Console.Write(inputstr[j]);
Console.WriteLine();
}
}
}
static public void Main ()
{
string inputstr = "Geeks" ;
find_Substring(inputstr, inputstr.Length);
}
}
|
Output:
G
e
e
k
s
Ge
ee
ek
ks
Gee
eek
eks
Geek
eeks
Geeks
Share your thoughts in the comments
Please Login to comment...