java 单词翻转

来源:互联网 发布:阿里云直播demo 编辑:程序博客网 时间:2024/05/18 00:43
 I am a student 中国

中国 student a am I 

先将每个单词反转,再将整体字符串反转

public class ReverseWords {private static String word;public ReverseWords(String str){this.word=str;}public void reverse(){int length=word.length();int begin=-1,end=-1;for(int i=0;i<length;i++){if(begin==-1&&word.charAt(i)==' ')//字符串开头有空格continue;if(begin==-1){//确定单词首位置begin=i;continue;}if(word.charAt(i)==' '){//确定单词尾end=i-1;}else if (i==length-1) {//遍历到字符串末尾end=i;}else {continue;}reverse(begin,end);begin=-1;end=-1;}reverse(0,length-1);}public void reverse(int begin,int end){char[] tmp=word.toCharArray();while(begin<end){tmp[begin]^=tmp[end];tmp[end]^=tmp[begin];tmp[begin]^=tmp[end];begin++;end--;}word=String.copyValueOf(tmp);}public static void main(String[] args) {ReverseWords reverseWords=new ReverseWords(" I am a student 中国");System.out.println(word);reverseWords.reverse();System.out.println(word);}}
结果:

 I am a student 中国
中国 student a am I