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:

class SubstringsOfStringMain
{
 public static void main(String args[])
 {
  String str="abbc";
  System.out.println("All substring of abbc are:");
   for (int i = 0; i < str.length(); i++) {
   for (int j = i+1; j <= str.length(); j++) {
         System.out.println(str.substring(i,j));
  
   }
  }
 }
}
When you run above program, you will get following output:
All substring of abbc are:
a
ab
abb
abbc
b
bb
bbc
b
bc
c
Above solution is of o(n^2) time complexity. As number of subString for n character String is n(n+1)/2, so we won't be able to get optimal solution than this.
If you want to find all distinct substrings of String,then use HashSet to remove duplicates.

Please go through Frequently asked java interview Programs for more such programs.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012