Reverse String Word by Word in Java

I have the following code to reverse a string word by word, I have a question though, first could anyone point at how to make it better code? and second, how can I remove the space that I end up with at the beginning of the new string.

String str = "hello brave new world";
tStr.reverseWordByWord(str)

public String reverseWordByWord(String str){
        int strLeng = str.length()-1;
        String reverse = "", temp = "";

        for(int i = 0; i <= strLeng; i++){
            temp += str.charAt(i);
            if((str.charAt(i) == ' ') || (i == strLeng)){
                for(int j = temp.length()-1; j >= 0; j--){
                    reverse += temp.charAt(j);
                    if((j == 0) && (i != strLeng))
                        reverse += " ";
                }
                temp = "";
            }
        }

        return reverse;
    }

the phrase at the moment becomes:

olleh evarb wen dlrow

notice the space at the beginning of the new string.


Solution 1:

Not using the split function the code would look like:

public static void reverseSentance(String str) {
    StringBuilder revStr = new StringBuilder("");
    int end = str.length(); // substring takes the end index -1
    int counter = str.length()-1;
    for (int i = str.length()-1; i >= 0; i--) {     
        if (str.charAt(i) == ' ' || i == 0) {
            if (i != 0) {
                revStr.append(str.substring(i+1, end));
                revStr.append(" ");
            }
            else {
                revStr.append(str.substring(i,end));
            }
            end = counter;
        }
        counter--;
    }
    System.out.println(revStr);
}

Solution 2:

If str = "The quick brown fox jumped over the lazy dog!" it will return it like "dog! lazy the over jumped fox brown quick The" ...

  private static String Reverse(String str) {
      char charArray[] = str.toCharArray();
    for (int i = 0; i <str.length(); i++){
        if(charArray[i] == ' ')
        return Reverse(str.substring(i + 1)) + str.substring(0, i) + " ";
    }

    return str + " ";
}

Solution 3:

Here's how you could do it:

    StringBuilder result = new StringBuilder();
    StringTokenizer st = new StringTokenizer(input, " ");
    while (st.hasMoreTokens()) {
        StringBuilder thisToken = new StringBuilder(st.nextToken());
        result.append(thisToken.reverse() + " ");
    }
    String resultString = result.toString();

Solution 4:

My approach using StringUtils. In a unit test.

@Test
public void testReversesWordsAndThenAllCharacters(){
    String sentence = "hello brave new world";
    String reversedWords = StringUtils.reverseDelimited(sentence, ' ');
    String reversedCharacters = StringUtils.reverse(reversedWords);
    assertEquals("olleh evarb wen dlrow", reversedCharacters);
}

If you static import StringUtils, this could be inlined to:

reverse(reverseDelimited("hello brave new world", ' '))