Java: How to split a string by a number of characters?

前端 未结 11 1440
夕颜
夕颜 2020-11-27 06:59

I tried to search online to solve this question but I didn\'t found anything.

I wrote the following abstract code to explain what I\'m asking:

String         


        
11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 07:29

    Here's a succinct implementation using Java8 streams:

    String text = "how are you?";
    final AtomicInteger counter = new AtomicInteger(0);
    Collection strings = text.chars()
                                        .mapToObj(i -> String.valueOf((char)i) )
                                        .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 4
                                                                    ,Collectors.joining()))
                                        .values();
    

    Output:

    [how , are , you?]
    

提交回复
热议问题