开发者

What is wrong with this code for printing reverse of a sentence while maintaining the order?

public String reverse(Strin开发者_StackOverflowg sentence){
    String reverse = "";
    char [] s = sentence.toCharArray();
    int first = s.length-1;
    int last = s.length-1;
    String temp = "";

    for(int i = s.length-1; i>=0; i--){
        temp = " ";
        while(s[first] != ' '){
            System.out.println(s[first]);
            first--;

        }
        while(last != first){
            temp = s[last] + temp;
            last--;
            i--; 
        }            
        reverse = reverse + temp;
    }
    return reverse;
}

My input is: Something for test.

Expected Output: test. for Something

My Actual Output: test.

Please let me know what is wrong with this? I know it's a long way to do but I was trying to minimise the use of readily available functions.


If you want to reverse the words in a sentence, I'll do it like this :

public String reverse(String sentence) {
    String[] words = sentence.split(" ");
    String ret = "";
    for(int i = words.length - 1; i >= 0; i--) {
        ret += words + " ";
    }
    return ret;
}

If you want to stick with your approach, you can use the lastIndexOf(int) method to find all spaces instead of looping on a CharSequence and then the subString method to extract each word.


When you loop for the first time and decrement first, at the end of the loop s[first] points to ' '. When you get into the the for loop the second time, the test

while(s[first] != ' ')

fails as s[first] still points to the ' ' that you stopped at the last time. Consequently you only get the very last word and nothing more.

Try decrementing first just before you end the loop.


It's giving that output because you're decrementing i here:

    while(last != first){
        temp = s[last] + temp;
        last--;
        i--; 
    }     

There are two ways to do this properly, but if you're going to do it this way, you should use whatever string library there is to cut the string up for you. On top of that, your current algorithm would cause first to go past 0, into the negatives, causing some sort of error, presumably.

public String reverse(String sentence){
    String reverse = "";
    char [] s = sentence.toCharArray();
    int first = s.length-1;
    int last = s.length-1;
    String temp = "";

    for(int i = s.length-1; i>=0; i--){
        while(s[first] != ' ' && first!=0){
            first--;
        }
        if (first!=0) temp = s.substring(first+1, last);
          else temp = s.substring(first, last);
        last=first;
        reverse = reverse + temp + " ";
    }

    return reverse;
}

If, for whatever reason, you don't want to use substring, and instead want to keep your original algorithm, then all it needs is the removal of the i--; line.

(I see someone else has posted an answer using split(" "), which would probably be even better.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜