开发者

Any Commons all substrings function?

开发者 https://www.devze.com 2023-02-14 21:29 出处:网络
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.

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开发者_如何学JAVA", "ab", "b", "abc", "bc", "c", "abcd", "bcd", "cd","d", "abcde", "bcde", "cde", "de", "e".


I don't believe there's a library function, but it would be extremely easy to just roll one youself:

public ArrayList<String> getAllSubstrings(String s)
{
   ArrayList<String> toReturn = new ArrayList<String>();
   for (int i = 0; i < s.length(); i++)
      for (int j = i + 1; j < s.length(); j++)
         toReturn.add(s.substring(i, j));
}

Remember though, that there will be a number of permutations equal to 1+2+3+4+...+s.length


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.


Sounds computational intensive. Think of all the permutations you would have with whole sentences.

That and they probably figured if somebody needed something that wasn't something needed on a regular basis.


public static ArrayList getPowerSet(String original) { ArrayList toReturn = new ArrayList();

   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;
}


public static ArrayList<String> getPowerSet(String original) {
       ArrayList<String> toReturn = new ArrayList<String>();

       toReturn.add("");

       for (int k = 0; k < original.length(); k++) {
          for (int j = k + 1; j <= original.length(); j++) {
             toReturn.add(original.substring(k, j));
          }
       }

       return toReturn;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消