All Possible Substrings Of A Given String In C#

Find All Substrings of a Given String in C#

We will learn how to find all substrings of a given string with an example.

For that, we will ask string from the user and generate substrings.

Let’s consider string is ABCD

The following steps are performed,

Step 1:

First, we get the input string from the user

Step 2:

The first loop (the outer loop) will then be defined, in which the first character of the substring will be kept.

Step 3:

The second loop (the inner loop) is then defined, and the substring is created by adding one character in each iteration until the string’s end is reached.

If the provided String is “ABCD,” for example, the first loop will keep the location of A, then B, C, and finally D.

The second loop will be substring the string into
For i=1: A, AB, ABC, then ABCD for the last iteration
For i=2: B, BC and then BCD
For i=3: C and then CD
For i=4: D

Step4: Print the substring

Program :

    //find all substring
    var orignalString;
    var newString="";
    var tempString="";
    console.log("Enter String :")
    orignalString=console.ReadLine();
      for(let i=0;i<orignalString.length;i++){
        tempString=orignalString[i];
        newString=newString+" "+tempString;
        for(let j=i+1;j<orignalString.length;j++)
        {
          tempString=tempString+orignalString[j];
          newString=newString+" "+tempString;
        }
        tempString="";
      }
      console.log(newString);

Output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories