Split string to equal length substrings in Java

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

    Here's a one-liner version which uses Java 8 IntStream to determine the indexes of the slice beginnings:

    String x = "Thequickbrownfoxjumps";
    
    String[] result = IntStream
                        .iterate(0, i -> i + 4)
                        .limit((int) Math.ceil(x.length() / 4.0))
                        .mapToObj(i ->
                            x.substring(i, Math.min(i + 4, x.length())
                        )
                        .toArray(String[]::new);
    

提交回复
热议问题