【发布时间】:2020-12-12 00:02:15
【问题描述】:
我被一个(可能非常简单的)想法难住了。我正在使用 BufferedReader 读取文本文件,并在空格处拆分字符串。我需要创建一个新的字符串数组,并将前一个数组中的 3s 单词中的新元素分组,例如{The, quick, brown, fox, jumped, over, the, lazy, cat} ⇒ {The quick brown, fox jumped over, the lazy cat}.
到目前为止,我提出了一个非常低效的尝试,它遍历数组并将元素和空格连接到一个新的字符串数组。它还会在新数组中留下空值,因为我每次都会增加 i+3。
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]);
}
}
输出示例:
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.
【问题讨论】: