Java – Find all Possible Substrings of a String

To find all substrings of a string, use a nested loop, where one of the loop traverses from one end of the string other, while the other loop changes the length of substring.

In this tutorial, we shall write Java programs to find all possible substrings of a string, and also to find all unique substrings of a string.

All Substrings of a String using Nested For Loop

Algorithm

We shall use following algorithm to find the substrings of a string.

  1. Start.
  2. Read string to str.
  3. Take an empty list allSubstrings to store all the substrings.
  4. Initialize len with 1.
  5. Check if len is less than or equal to string str length. If false, go to step 11.
  6. Initialize index with 0.
  7. Check if index is less than or equal to the difference of string str length and len. If false go to step 10.
  8. Add the substring of str, with start as index and end as index+len, to allSubstrings.
  9. Increment index. Go to step 7.
  10. Increment len. Go to step 5.
  11. allSubstrings has all the substrings. You may print them.
  12. Stop.

Example.java

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Java Program - All Substrings
 */

public class Example {

	public static void main(String[] args) {

		String str = "apple";
		
		List<String> allSubstrings = new ArrayList<String>();
		
		for(int len=1; len<=str.length(); len++) { //length of substring
			for(int index=0;index<=str.length()-len;index++) { //traverse along substring
				allSubstrings.add(str.substring(index, index+len));
			}
		}
		
		System.out.println(Arrays.toString(allSubstrings.toArray()));		
	}

}

Output

[a, p, p, l, e, ap, pp, pl, le, app, ppl, ple, appl, pple, apple]
ADVERTISEMENT

All Unique Substrings of a String

To store only unique substrings, instead of a Java List, use Java HashSet to store the substrings in the nested loop.

Example.java

import java.util.Arrays;
import java.util.HashSet;

/**
 * Java Program - All Substrings
 */

public class Example {

	public static void main(String[] args) {

		String str = "apple";
		
		HashSet<String> allSubstrings = new HashSet<String>();
		
		for(int len=1; len<=str.length(); len++) { //length of substring
			for(int index=0;index<=str.length()-len;index++) { //traverse along substring
				allSubstrings.add(str.substring(index, index+len));
			}
		}
		
		System.out.println(Arrays.toString(allSubstrings.toArray()));		
	}

}

Output

[a, p, p, l, e, ap, pp, pl, le, app, ppl, ple, appl, pple, apple]

Conclusion

In this Java Tutorial, we learned how to find all substrings of a given string, with the help of Java programs.