今天来看看如何实现字符串反转,比如输入Game is Over,输出Over is Game


public class Question {
public static void main(String[] args) {
String str = "Game is over adfd aaaa cccc";
System.out.println("============="+reverseStr(str));
}

private static String reverseStr(String str) {
//当前字符串
String temp = str;
StringBuilder sb = new StringBuilder();
//每个空格的位置,从后向前查找
int index = temp.lastIndexOf(" ");
//循环查找空格是否存在
while (index != -1) {
//每个空格之后的字符串
String subStr = temp.substring(index, temp.length());
sb.append(subStr);
//空格之前的字符串
String lastStr = temp.substring(0,index);
//剩下字符串中空格的位置
index = lastStr.lastIndexOf(" ");
//没有空格,说明到了最后一个单词,进行添加并且需要手动添加一个空格和前面的单词隔开
if (index == -1) {
sb.append(" ").append(lastStr);
}
temp = lastStr;
}
//除去第一个空格
sb.replace(0,1,"");
return sb.toString();
}
}