java算法求一个字符串的倒序(单词不变)

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

 

你可能感兴趣的:(代码)