首页 > 解决方案 > How to split a String array at every nth word?

问题描述

I'm stumped on a (probably very simple) idea. I am reading in a text file with a BufferedReader, and splitting the string at whitespaces. I need to create a new string array and group the new elements in words of 3s from the previous array e.g. {The, quick, brown, fox, jumped, over, the, lazy, cat}{The quick brown, fox jumped over, the lazy cat}.

So far I have come up with a very inefficient attempt that iterates over the array and concatenates elements and whitespaces to a new string array. It also leaves nulls in the new array because I am incrementing by i+3 each time.

String line = "";
while ((line = br.readLine()) != null) {
    String words[] = line.split(" ");
    String[] result = new String[words.length - 1];

    for (int i = 0; i < words.length - 3; i += 3) {
        result[i] = words[i] + " " + words[i + 1] + " " + words[i + 2];
    }
    for (int i = 0; i < result.length; i++) {
        System.out.println(result[i]);
    }
}

An example of the output:

a Goose who null null was taking a null null walk by the null null side of the null null "Good heavens!" cried null null the Goose.

标签: javaarraysstring

解决方案


您可以iterate使用包含三个元素的步骤来覆盖此数组的索引,并在每个步骤中使用Arrays.stream(T[],int,int)方法来获取从当前元素到下一个第三元素的元素范围,并使用joining空格分隔符将它们连接起来:

String[] arr = {
        "The", "quick", "brown",
        "fox", "jumped", "over",
        "the", "lazy", "cat"};
String[] arr2 = IntStream
        // every third element 0, 3, 6
        .iterate(0, i -> i < arr.length, i -> i + 3)
        // stream over the elements of the array with
        // a range from the current element to the next
        // third element, or the end of the array
        .mapToObj(i -> Arrays.stream(arr, i, Math.min(i + 3, arr.length))
                // join elements with whitespace delimiter
                .collect(Collectors.joining(" ")))
        // return an array
        .toArray(String[]::new);
// output line by line
Arrays.stream(arr2).forEach(System.out::println);
// The quick brown
// fox jumped over
// the lazy cat

推荐阅读