Print all substrings of a given string

Objec­tive:  Given a string write an algorithm to print all the possible sub strings.

Example:

String input = “abcd”;
Output: Possible sub strings –

a          a b      a b c   a b c d
b          b c      b c d
c          c d
d

Approach:
  • Use nested loops.
  • Outer loops will decide the starting point.
  • First inner loops will decide the group size. Starting from 1 and goes up string character array size.
  • Most inner loop will create the sub strings and print it.
  • See the code below for more understanding.

Complete Code: <


public class PrintAllSubStrings {
public void print(String input){
int length = input.length();
//start point
for (int startPoint = 0; startPoint <length ; startPoint++) {
//group sizes
for (int grps = startPoint; grps <=length ; grps++) {
//if start point = 1 then
//grp size = 1 , print 1
//grp size = 2, print 1 2
//grp size = 3, print 1 2 3 ans so on
for (int j = startPoint ; j < grps ; j++) {
System.out.print(input.charAt(j) + " ");
}
System.out.println();
}
}
}
public static void main(String[] args) {
String input = "abcd";
new PrintAllSubStrings().print(input);
}
}


Output:

a
a b
a b c
a b c d
b
b c
b c d
c
c d
d

1 thought on “Print all substrings of a given string”

  1. We can exclude one extra for loop

    for (c = 0; c < length; c++)
    {
    for(i = 1; i <= length – c; i++)
    {
    sub = string.substring(c, c+i);
    System.out.println(sub);
    }
    }

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.