In this short article, we are going to showcase how to find all substrings of a string in Java.

First, we will start by showing how to do this using core Java methods. Then, we are going to highlight how to achieve the same thing using external libraries.

Java provides several methods and classes to print all possible substrings of a given string. So, let’s take a close at each approach.

Using String.substring() Method

substring() offers the easiest way to get substrings from an original string.

So, let’s illustrate how we can use it using a practical example:

    
        String str = "Hello";
        List<String> substringList = new ArrayList<String>();
        for (int i = 0; i <= str.length(); i++) {
            for (int j = i + 1; j <= str.length(); j++) {
                substringList.add(str.substring(i, j));
            }
        }
        System.out.println(substringList);
    

using substring method

As we can see, we used two loops. Since the substring() method has a time complexity of o(n), the above approach has a o(n^3) time complexity.

Using StringBuffer Class

Similarly, we can use the StringBuffer class to extract all the substrings. However, the time complexity will jump to O(n)2.

So, let’s exemplify the use of the StringBuffer class:

    
        String str = "foo";
        int length = str.length();
        char[] strChars = str.toCharArray();

        List<String> substringList = new ArrayList<String>();
        int i = 0;
        while (i < length) {
            StringBuffer buildStr = new StringBuffer();
            buildStr.append(strChars[i]);
            for (int j = i + 1; j <= length; j++) {
                substringList.add(buildStr.toString());
                if (j < length) {
                    buildStr.append(strChars[j]);
                }
            }
            i++;
        }

        System.out.println(substringList);
    

The program will produce the output:

    
        [f, fo, foo, o, oo, o]
    

We used the toCharArray() method to convert a string into a char[] array. Then, we used the StringBuffer class to build all the possible portions.

Alternatively, another solution would be using the StringBuilder class. The only difference is that StringBuilder is not thread-safe.

Using Apache Commons Lang Library

This external library comes with a set of ready-to-use utility classes. Among these classes, we find the StringUtils.

As the name indicates, it’s a utility class that provides a convenient way to operate on strings in a null-safe manner.

So, let’s see it in action:

    
        String str = "bar";
        int strLength = StringUtils.length(str);

        for (int i = 0; i <= strLength; i++) {
            for (int j = i + 1; j <= strLength; j++) {
                System.out.println(StringUtils.substring(str, i, j));
            }
        }
    

As shown above, we used StringUtils.length() to get the length of the original string.

Then, we used the StringUtils.substring() method to find all the possible substrings.

Find all Unique Substrings

Now, let’s see how to print all the possible unique subregions of a particular string.

Typically, we can use a HashSet implementation to achieve this. By design, HashSet does not accept duplicate values:

    
        import java.util.HashSet;
        import java.util.Iterator;
        import java.util.Set;
        public class UniqSubstrings {
            public UniqSubstrings() {
            }
            public static void main(String[] args) {
                String str = "deev";
                Set<String> uniqSubs = new HashSet<String>(); 
                for (int i = 0; i <= str.length(); i++) { 
                    for (int j = i + 1; j <= str.length(); j++) { 
                        uniqSubs.add(str.substring(i, j)); 
                    } 
                } 
                Iterator<String> siterator = uniqSubs.iterator();
                while(siterator.hasNext()){
                    System.out.println(siterator.next());
                }
            }
        }
    

The above program will output:

    
        ee
        de
        ev
        d
        dee
        e
        v
        eev
        deev
    

Conclusion:

To sum it up, we have showcased how to find all substrings of a string in Java.

Along the way, we illustrated how to do this using built-in Java methods and classes.

Then, we explained how to accomplish the same objective using Apache Commons library.