Reputation: 189
What is the most efficient way to split a string into an array of its suffixes?
Say you have the string "The weather is nice", I want to generate an array of its suffixes as such:
[0] = "nice"
[1] = "is nice"
[2] = "weather is nice"
[3] = "the weather is nice"
I have access to the strings in the form of an iterator over its tokens (words) from start to end.
Upvotes: 4
Views: 414
Reputation: 1382
The obvious solution is to tokenize the string on spaces and store the result in a ListArray<String>
in reverse order. Then build your answer ListArray
from that, a little recursion is good for the soul..
Upvotes: 0
Reputation: 726919
Split the array on spaces using the split
, then go through the resultant tokens back-to-front, take the previous suffix, and prepend the current token to its front. If there is no prior suffix, use an empty string:
String str = "quick brown fox jumps over the lazy dog";
List<String> res = new ArrayList<String>();
String last = null;
String[] tok = str.split(" ");
for (int i = tok.length-1 ; i >= 0 ; i--) {
if (last == null) {
last = tok[i];
} else {
last = tok[i] + " " + last;
}
res.add(last);
}
for (String s : res) {
System.out.println(s);
}
This prints
dog
lazy dog
the lazy dog
over the lazy dog
jumps over the lazy dog
fox jumps over the lazy dog
brown fox jumps over the lazy dog
quick brown fox jumps over the lazy dog
Upvotes: 7
Reputation: 61
Calling .split(" "); will return an array of the words in the string.
Upvotes: 0