Split string to equal length substrings in Java

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

    Here is a one liner implementation using Java8 streams:

    String input = "Thequickbrownfoxjumps";
    final AtomicInteger atomicInteger = new AtomicInteger(0);
    Collection result = input.chars()
                                        .mapToObj(c -> String.valueOf((char)c) )
                                        .collect(Collectors.groupingBy(c -> atomicInteger.getAndIncrement() / 4
                                                                    ,Collectors.joining()))
                                        .values();
    

    It gives the following output:

    [Theq, uick, brow, nfox, jump, s]
    

提交回复
热议问题