java用算法实现字符串中的字符顺序改变

来源:百度知道 编辑:UC知道 时间:2024/06/17 08:19:41
比如: input string = "Hello the world"
output 就是: "world the Hello"
特别是空格也是要处理
谢谢

public class Reverse {
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();
}
}

========================测试结果
world the Hello
sdf中 sdfsdfsadf sdfsadf sdfsdf a

public class StringReverse
{
public static void main(String[] args)
{ System.out.println(rev("Hello World!")); }
public static String rev(String str)
{ ch