Split string to equal length substrings in Java

后端 未结 21 1876
日久生厌
日久生厌 2020-11-22 02:56

How to split the string \"Thequickbrownfoxjumps\" to substrings of equal size in Java. Eg. \"Thequickbrownfoxjumps\" of 4 equal size should give th

21条回答
  •  再見小時候
    2020-11-22 03:34

    Java 8 solution (like this but a bit simpler):

    public static List partition(String string, int partSize) {
      List parts = IntStream.range(0, string.length() / partSize)
        .mapToObj(i -> string.substring(i * partSize, (i + 1) * partSize))
        .collect(toList());
      if ((string.length() % partSize) != 0)
        parts.add(string.substring(string.length() / partSize * partSize));
      return parts;
    }
    

提交回复
热议问题