如何反转字符串中的单词但将标点符号保留在正确的位置? [英] How to reverse words in a string but keep punctuation in the right place?

查看:71
本文介绍了如何反转字符串中的单词但将标点符号保留在正确的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have written the following code to reverse an input String:

  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);

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

However it is not giving me the result I want. I need the punctuation to be part of the word it is attached to, but still to switch to the right side of the word. For example if you input

敏捷的棕色狐狸跳过懒惰的狗"

"The quick brown fox jumps over the lazy dog"

我希望输出为

狗懒过跳过狐狸棕色快了"

"dog lazy the over jumps fox brown quick The"

我实际得到的是:

狗"懒惰的跳过狐狸棕色快速的

dog" lazy the over jumps fox brown quick "The

推荐答案

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

If you just want to handle double quotes at the start and end of the input, just reverse the substring and add them later. E.g.

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

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

and finally after splitting, reversing and concatenating print:

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

还有 2 条建议:

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

1) Your for loop leaves a trailing space. Don't add a space for the last word
2) You should use a StringBuilder to concatenate strings. E.g.

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() + '"');

这篇关于如何反转字符串中的单词但将标点符号保留在正确的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆