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
Link to a demo on ideone.