java - 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.
解决方案
您可以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
推荐阅读
- bash - Bash:获取打印函数的状态
- javascript - How to display an array of pair arrays as key values pairs?
- deployment - 我如何知道谷歌云何时完成部署我的网站?
- robotframework - 如何在控制台错误时停止机器人框架套件的执行?
- android - android联系人中的is_primary标志何时设置为非零值?
- c# - 母版页不会在 Web 窗体上显示其内容
- vue.js - Vue.js 和 VueRouter 性能缓慢
- spring-boot - 如果@Scheduled 注解的方法在两台不同的机器上运行,它会被调用两次吗?
- sql - json字段上的PosgtreSQL连接表
- mongodb - 日期标准不适用于使用spring数据的mongodb