public class Test {
public static void main(String[] args){
String s="i am happy";
System.out.println(new Test().swapWords(s));
}
public String swapWords(String s){
if(s==null||s.length()==0)
return null;
//字符串转换为数组
char[] chs = s.toCharArray();
int len=chs.length;
//1,实现整个字符串反转:"i am happy"--->"yppah ma i"
swap(chs,0,len-1);
//2,实现单词反转:"yppah ma i"--->"i am happy"
int begin=0;
for(int i=1;i<len;i++){
if(chs[i]==' '){
swap(chs,begin,i-1);
begin=i+1;
}
}
swap(chs,begin,len-1);
//数组转换为字符串
return new String(chs);
}
//逆序
public void swap(char[] ch,int front,int end){
while(front<end){
char temp=ch[end];
ch[end]=ch[front];
ch[front]=temp;
front++;
end--;
}
}
}