首页 > 解决方案 > 在Java中反转句子

问题描述

标签: javastringif-statementcharsubstring

解决方案


你可以简单地做到这一点

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

推荐阅读