反向打印字符串单词-边缘情况

时间:2019-07-01 16:06:21

标签: java string

我尝试创建一个将字符串从StackOverflow is the best.更改为best. the is StackOverflow的函数。

我编写了以下函数,但似乎无法修复result字符串中的空格。由于某种原因,我收到了best.the is Stackoverflowbest.the之间没有空格,并且StackOverflow之后有多余的空格。

我可以添加一个表示空间的变量,并在边缘情况下使用if,但是我相信这样做有更好的方法。

有人可以帮我解决这个问题吗?

public static void main(String[] args) {
    String str = "Stackoverflow is the best.";

    String result = change(str);

    System.out.println(result);
}



private static String change(String str) {
    String result = "";

    int i1 = str.length()-1;
    int i2 = str.length();

    for (i1 = str.length(); i1 >= 0; i1--) {

        if (i1 ==0 || str.charAt(i1-1) == ' ') {

            result = result.concat(str.substring(i1, i2));
            i2 = i1;
        }           
    }

return result;
}

3 个答案:

答案 0 :(得分:1)

我不使用if's可以想到的一种方法是:

        String line = "Stackoverflow is the best.";
        String delimeter = " ";
        final String[] words = line.split(delimeter);
        String reversedLine = "";
        for(int i = words.length - 1; i >= 0; i--) {
            reversedLine += words[i] + delimeter;
        }
        // remove the delimeter present at last of line
        reversedLine = reversedLine.substring(0, reversedLine.length() - 1);
        System.out.println(reversedLine);

答案 1 :(得分:0)

要生成您所提到的输出,我将以这种方式处理问题:

class Solution {
  public static void main(String[] args) {
    String str = "StackOverflow is the best.";
    String[] arr = str.split(" ");
    System.out.print(arr[arr.length-1]);
    for(int i = arr.length - 2; i >= 0; i--){
      System.out.print(" "+arr[i]);
    }
  }
}

答案 2 :(得分:-2)

出现问题的唯一原因是您尚未在“。”之后添加空格。 尝试使用String str = "Stackoverflow is the best. ";

希望对您有帮助...:)

相关问题