【问题标题】:How to reverse words in a string but keep punctuation in the right place? [duplicate]如何反转字符串中的单词但将标点符号保留在正确的位置? [复制]
【发布时间】:2015-11-24 17:00:11
【问题描述】:

我编写了以下代码来反转输入字符串:

  Scanner s = new Scanner(System.in);
  System.out.println("Please enter a sentence:");
  String sentence = s.nextLine();

  String[] words = sentence.split(" ");
  String reversedSentence = "";

  for(int i = words.length - 1; i >= 0 ; i--)
  {
      reversedSentence += words[i] + " ";
  }

  System.out.println(reversedSentence);

但是它并没有给我想要的结果。我需要标点符号成为它所附加的单词的一部分,但仍要切换到单词的右侧。例如,如果您输入

“敏捷的棕狐跳过懒狗”

我希望输出是

“狗懒得翻越狐狸皮快了”

我实际得到的是:

dog”懒洋洋地跳过狐狸棕色快“The

【问题讨论】:

  • 您只对开头和结尾的引号感兴趣?句中的标点符号呢?
  • 看起来像一个你必须处理的特殊情况。您可以输入if (words[0].contains("\"")) 来检查是否存在双引号。您可能希望在 for 循环之后执行此操作。
  • 在'System.out.println(reversedSentence);'之前添加行'reversedSentence = "\"" + reversedSentence.replace("\"", "") + "\"";'

标签: java string reverse


【解决方案1】:

如果您只想在输入的开头和结尾处理双引号,只需反转子字符串并稍后添加它们。例如

if (sentence.startsWith("\"") && sentence.endsWith("\"")) {
    sentence = sentence.substring(1, sentence.length()-1);
}

最后在拆分、反转和连接打印之后:

System.out.println('"' + reversedSentence + '"');

还有 2 条建议:

1) 你的 for 循环留下一个尾随空格。最后一个单词不要加空格
2)您应该使用StringBuilder 来连接字符串。例如

StringBuilder reversedSentence = new StringBuilder();

for (int i = words.length - 1; i > 0; i--) {
    reversedSentence.append(words[i]).append(' ');
}
reversedSentence.append(words[0]);
System.out.println('"' + reversedSentence.toString() + '"');

【讨论】:

  • 在此答案的顶部,子字符串参数不正确,因为子字符串接受 (int inclusive, int exclusive) 所以它应该是: if (sentence.startsWith("\"") && sentence .endsWith("\"") { sentence = sentence.substring(1, sentence.length()-1); }
【解决方案2】:

如果标点符号也打开和关闭。就像你的例子一样。你可以使用这样的东西:

很脏。我稍后会编辑它。我不怎么做java。

    String[][] punctuations = new String[][] {
            {"(", ")"},
            {"“", "”"}
    };

    for (String[] punctuation : punctuations) {
        if (sentence.contains(punctuation[0])) {
            int index_0 = sentence.indexOf(punctuation[0]);
            int index_of_next_space = sentence.indexOf(" ", index_0);
            String old_string_0 = sentence.substring(index_0, index_of_next_space);
            String new_string_0 = old_string_0.replace(punctuation[0], "") + punctuation[1];

            int index_1 = sentence.indexOf(punctuation[1]);
            int index_of_last_space = sentence.lastIndexOf(" ", index_1);
            String old_string_1 = sentence.substring(index_of_last_space+1, index_1 + 1);
            String replaced_string_1 = punctuation[0] + old_string_1.replace(punctuation[1], "");
            sentence = sentence.replace(old_string_0, new_string_0);
            sentence = sentence.replace(old_string_1, replaced_string_1);
        }
    }

现在反转你的字符串。

输入:

“(快布朗的)狐狸跳过懒狗”

输出:

“狗懒得过跳狐狸(布朗的快)”

这可以改进。就像我之前说的,我不怎么做 java :/.

【讨论】:

    【解决方案3】:

    将字符串分解成数组并使用Collections.reverse(),如下:

    public class StringReverse {
    
     public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            System.out.println("Please enter a sentence:");
            String sentence = s.nextLine();
            String[] array = sentence.replaceAll("\\“|”", "").split(" ");
            StringBuilder sb = new StringBuilder();
            List<String> list = Arrays.asList(array);
            Collections.reverse(list);
            array = (String[]) list.toArray();
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]).append(" ");
            }
            System.out.println(sentence.charAt(0)
                    + sb.toString().replaceAll(" $", "")
                    + sentence.charAt(sentence.length() - 1));
            s.close();
        }
    }
    

    使用 Java 8 Arrays.stream,就这么简单:

    import java.util.ArrayDeque;
    import java.util.Arrays;
    import java.util.Scanner;
    import java.util.stream.Collectors;
    
    public class StringReverse {
    
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter a sentence:");
        String sentence = s.nextLine();
        StringBuilder sb = new StringBuilder();
        Arrays.stream(sentence.replaceAll("\\“|”", "").split(" "))
                .collect(Collectors.toCollection(ArrayDeque::new))
                .descendingIterator()
                .forEachRemaining(e -> sb.append(e).append(" "));
        System.out.println(sentence.charAt(0)
                + sb.toString().replaceAll(" $", "")
                + sentence.charAt(sentence.length() - 1));
        s.close();
    }
    

    【讨论】:

    • 下次在回答之前阅读问题。
    • @RaghavSharma:由于代码格式问题,错过了引号,现在已经修复了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    相关资源
    最近更新 更多