在 Java 中反转句子

Reverse a sentence in Java

The question for homework is the program should print the String in reverse word by word.
Your `String' should be assigned the value “pay no attention to that man behind the curtain” and should be printed as the sample output.

在编译时出现错误,并为此花费了 3 个小时 - 迷路了!

我必须使用 charAt 方法、substring 方法和一个 if 语句:

curtain
the
behind
man
that
to
attention
no
pay

public class backwards
{
    public static void main(String args[])
    {
        String s1 = new String("pay no attention to that man behind the curtain");

        /*int pos = s1.indexOf(' ');
        while(s1.length() >  0)
        {
            if(pos == -1)
            {
                System.out.println(s1);
                s1 = "";

            }
            else
            {
                System.out.println(s1.substring(0,pos));
                s1 = s1.substring(pos+1);
                pos = s1.indexOf(' ');
            }

        }*/
        int pos = 0;
        for(int i = s1.length()-1 ; i >= 0; i--)
        {
        //  System.out.println("Pos: " + pos);
            if(s1.charAt(i) == ' ')
            {
                System.out.println(s1.substring(i+1));
                s1 = s1.substring(0,i);
            }
            else if(i == 0)
            {
                System.out.println(s1);
                s1 = "";
            }
        }
    }
}

你可以像

一样简单地做到这一点
public class Main {
    public static void main(String[] args) {
        // Split on whitespace
        String[] arr = "pay no attention to that man behind the curtain".split("\s+");

        // Print the array in reverse order
        for (int i = arr.length - 1; i >= 0; i--) {
            System.out.println(arr[i]);
        }
    }
}

输出:

curtain
the
behind
man
that
to
attention
no
pay

或者,

public class Main {
    public static void main(String[] args) {
        String s1 = "pay no attention to that man behind the curtain";
        for (int i = s1.length() - 1; i >= 0; i--) {
            if (s1.charAt(i) == ' ') {
                // Print the last word of `s1`
                System.out.println(s1.substring(i + 1));

                // Drop off the last word and assign the remaining string to `s1`
                s1 = s1.substring(0, i);
            } else if (i == 0) {
                // If `s1` has just one word remaining
                System.out.println(s1);
            }
        }
    }
}

输出:

curtain
the
behind
man
that
to
attention
no
pay