【问题标题】:Reverse a sentence in Java [duplicate]在Java中反转句子[重复]
【发布时间】:2020-12-30 10:26:09
【问题描述】:

作业的问题是程序应逐字打印String
您的 `String' 应该被赋值为“不要注意幕后的那个人”,并且应该作为示例输出打印出来。

编译时出错并在此工作了 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 = "";
            }
        }
    }
}

【问题讨论】:

    标签: java string if-statement char substring


    【解决方案1】:

    你可以这样做

    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
    

    【讨论】:

    • 不错的代码。伟大的思想。等等等等。
    • 非常感谢 - 代码看起来更简洁,但我必须使用 charAt 方法、子字符串方法和 if 语句 - 否则根据分配标准代码是错误的
    • 非常感谢 - 替代工作@ArvindKumarAvinash
    • 不客气,@Topps
    猜你喜欢
    • 2017-05-19
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多