我正在使用此代码来颠倒句子的顺序,但是它也可以颠倒字符的顺序。在这里为我提供帮助,以使字符不会被颠倒,只有单词会被颠倒。例如“猫在跑”->“猫在跑”
public static void main(String[] args) {
String sentence = "Cat Is Running";
System.out.println(reverse(sentence));
}
public static String reverse(String str) {
if(str.isEmpty())
return str;
else {
return reverse(str.substring(1)) + str.charAt(0);
}
}
尝试一下:
public static void main(String[] args) {
String sentence = "Cat Is Running";
reverse(sentence);
}
public static void reverse(String str) {
int spaceIndex = str.lastIndexOf(" ");
if(spaceIndex == -1){
System.out.println(str+" ");
return;
}
System.out.print(str.substring(spaceIndex+1) + " ");
reverse(str.substring(0,spaceIndex));
}