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.
- Start.
- Read string to
str
. - Take an empty list
allSubstrings
to store all the substrings. - Initialize
len
with1
. - Check if
len
is less than or equal to stringstr
length. If false, go to step 11. - Initialize
index
with0
. - Check if
index
is less than or equal to the difference of stringstr
length andlen
. If false go to step 10. - Add the substring of
str
, with start asindex
and end asindex+len
, toallSubstrings
. - Increment index. Go to step 7.
- Increment len. Go to step 5.
allSubstrings
has all the substrings. You may print them.- Stop.
Example.java
</>
Copy
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]
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
</>
Copy
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.