您的函数的修改版本,使用String#lastIndexOf
:
String reverseMe(String s)
{
if (s.length() == 0)
return "";
int index = s.lastIndexOf(" ");
if (index == -1) // not found, thus just return the string
return s;
else // found, thus concat last part with recursive call
return s.substring(index + 1) + " " + reverseMe(s.substring(0, index));
}
或者您可以使用String#split
空格分隔,然后反向循环并连接。
String reverse(String s)
{
String reversed = "";
String[] split = s.split(" ");
reversed = split[split.length-1];
for (int i = split.length-2; i >= 0; i--)
{
reversed += " " + split[i];
}
return reversed;
}
尽管StringBuilder会成为一个更有效的选择,因为它不需要所有的字符串复制。