<分区>
我编写了以下代码来反转输入字符串:
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);
但是它没有给我想要的结果。我需要标点符号成为它所附单词的一部分,但仍要切换到单词的右侧。例如,如果您输入
“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