java 单词翻转

12 篇文章 0 订阅
11 篇文章 0 订阅
 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 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值