Find all substrings of a String in java

In this post, we will see java program to find all substrings of a String.
For example: If input is “abb” then output should be “a”, “b”,”b”, “ab”, “bb”, “abb”

We will use String class’s subString method to find all subString

Program:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

classSubstringsOfStringMain

{

publicstaticvoidmain(Stringargs[])

{

Stringstr="abbc";

System.out.println("All substring of abbc are:");

for(inti=0;i<str.length();i++){

for(intj=i+1;j<=str.length();j++){

System.out.println(str.substring(i,j));

}

}

}

}

When you run above program, you will get following output:

1

2

3

4

5

6

7

8

9

10

11

12

13

All substring of abbc are:

a

ab

abb

abbc

b

bb

bbc

b

bc

c

Above solution is of o(n^3) time complexity. As we have two loops and also String’s substring method has a time complexity of o(n)
If you want to find all distinct substrings of String,then use HashSet to remove duplicates.