This is another version that will reverse each word in place
package asaf;
public class ReverseWordsInString {
public static void main(String[] args) {
System.out.println(reverse(new StringBuffer("Reverse all the words in a string!")));
}
private static StringBuffer reverse(StringBuffer s) {
int fromIndex = 0;
int toIndex;
boolean reachTheEnd = false;
do {
toIndex = s.indexOf(" ", fromIndex);
if (toIndex == -1) {
reachTheEnd = true;
toIndex=s.length();
}
reverseWord(s, fromIndex, toIndex-1);
fromIndex = toIndex + 1;
} while (!reachTheEnd);
return s;
}
private static void reverseWord(StringBuffer s, int start, int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start++, s.charAt(end));
s.setCharAt(end--, temp);
}
}
}
// will print "esreveR lla eht sdrow ni a !gnirts"