Search code examples
javasubstringapache-commonscode-reuseapache-stringutils

Any Commons all substrings function?


I'm wondering if there's a library function (or why StringUtils in Apache Commons doesn't have it?) that for a String calculates all the substrings. For "abcde" it retuns "a", "ab", "b", "abc", "bc", "c", "abcd", "bcd", "cd","d", "abcde", "bcde", "cde", "de", "e".


Solution

  • I don't think AndyPerfect's will work correctly. The second loop bound needs to be <= instead of just <.

    public static ArrayList<String> getPowerSet(String original) {
           ArrayList<String> toReturn = new ArrayList<String>();
    
           toReturn.add("");
    
           for (int i = 0; i < original.length(); i++) {
              for (int j = i + 1; j <= original.length(); j++) {
                 toReturn.add(original.substring(i, j));
              }
           }
    
           return toReturn;
        }
    

    Note that you can remove that first add() if you don't want the empty substring included.