Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse String Word by Word in Java

Tags:

java

string

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.

like image 458
Tsundoku Avatar asked Feb 02 '12 00:02

Tsundoku


2 Answers

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);
}
like image 198
Califax Avatar answered Oct 14 '22 08:10

Califax


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 + " ";
}
like image 40
girman Avatar answered Oct 14 '22 06:10

girman