java算法求一个字符串的倒序(单词不变输出world the Hello)

时间:2022-08-02 10:55:49
public class TestString88 {
public static void main(String[] args) {
System.out.println(reverse("Hello the  world"));
System.out.println(reverse("a sdfsdf sdfsadf sdfsdfsadf sdf中"));
}


public static String reverse(String str) {
String temp = "";
StringBuffer buf = new StringBuffer();
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
if (c == ' ') {
buf.append(temp);
buf.append(c);
temp = "";
} else {
temp = c + temp;
}
}
buf.append(temp);
return buf.toString();
}
}