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.