翻译句子而不是字母

时间:2017-07-09 09:11:13

标签: javascript java netbeans

我想制作一个程序来反转单词,而不是字母。

例如......

i love india

......应该成为......

india love i

另一个例子......

 google is the best website

......应该成为......

 website best the is google

有了空格,我已经对它进行了彻底的研究,但却一无所获 我的逻辑是,我应该给你我的程序不起作用。如果您在我的代码中发现一个小错误,请为其提供解决方案并更正我的程序。另外,如果你不是太忙,可以请你在流程图中给我逻辑。

[basic.lookup.qual/3]

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

1。 将每行的单词存储在字符串数组中。 2。 将数组的元素从最后一项打印到第一项。

答案 1 :(得分:0)

class Solution {
     public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
         }

    // split to words by space
    String[] arr = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = arr.length - 1; i >= 0; --i) {
        if (!arr[i].equals("")) {
            sb.append(arr[i]).append(" ");
        }
    }
    return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
  }
}