Split string to equal length substrings in Java

后端 未结 21 1877
日久生厌
日久生厌 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:13

    i use the following java 8 solution:

    public static List splitString(final String string, final int chunkSize) {
      final int numberOfChunks = (string.length() + chunkSize - 1) / chunkSize;
      return IntStream.range(0, numberOfChunks)
                      .mapToObj(index -> string.substring(index * chunkSize, Math.min((index + 1) * chunkSize, string.length())))
                      .collect(toList());
    }
    

提交回复
热议问题