Suppose the string is "Hello world!" and now you want to change it to "! World Hello "
problem : The difficulty of this problem is how to ensure that the word is not reversed when the string is reversed
Problem Solving :
The first method of solution. First, the word is reversed, and then the string is reversed;
The second method of solution. First, the string is reversed, and then the word is reversed;
This is only the second solution:
* Core Code section: * *
public void reverse(String s){ StringBuffer stringBuffer = new StringBuffer(s); String a = stringBuffer.reverse().toString();//将字符串逆置 String[] b = a.split("\\s+");//分理出其中的非空格部分 stringBuffer = new StringBuffer(); for(String c:b){ StringBuffer stringBuffer1 = new StringBuffer(c); stringBuffer.append(" "+stringBuffer1.reverse.toString());//此处双引号里面的空格不可少 } System.out.print(stringBuffer.toString()); }
Word swapping in Java implementation strings