Java – the word reversion of a string

I want to reverse the words in the string I try to do it like this:

public String reverseWords(String str) {
    String reverse = "";
    String[] arr = str.split(" ");
    for (int i = arr.length; i < 0; i++) {
        reverse+=arr[i];
    }       
    return reverse;
}

But won't it give me anything in return? What do I suggest? Did I do wrong?

Solution

You have to iterate backwards Use – and you don't need to go from 0 to length, but from length to 1 This is the main logic of the manual reverse function

Try this:

public static String reverseWords(String str) {
    StringBuilder sb = new StringBuilder(str.length() + 1);
    String[] words = str.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
        sb.append(words[i]).append(' ');
    }
    sb.setLength(sb.length() - 1);  // Strip trailing space
    return sb.toString();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>