汉字与英文的互相转换

下面的两个方法用来解决乱码问题非常有用.

 

将包含汉字的字符串转换成英文:

/**
	 * 将中英文字串转换成纯英文字串 
	 * @param str
	 * @return
	 */
	public static String toTureAsciiStr(String str) {
		StringBuffer sb = new StringBuffer(); 
		byte[] bt = str.getBytes(); 
		
		for(int i =0 ;i<bt.length;i++){
			if(bt[i]<0){
				//是汉字去高位1 
				sb.append((char)(bt[i] & 0x7F)); 
			}else{
				//是英文字符 补0作记录
				sb.append((char)0);
				sb.append((char)bt[i]);
			} 
		}
		return sb.toString(); 
	}

 将转换后的字符串还原:

/**
	 * 将经转换的字串还原 
	 * @param str
	 * @return
	 */
	public static String unToTrueAsciiStr(String str){
		byte[] bt = str.getBytes();
		int i,l=0,length = bt.length,j=0; 
		for(i = 0;i<length;i++){
			if(bt[i] == 0){
				l++;
			}
		} 
		byte[] bt2 = new byte[length-l]; 
		for(i =0 ;i<length;i++){
			if(bt[i] == 0){
				i++;
				bt2[j] = bt[i];
			}else{
				bt2[j] = (byte)(bt[i]|0x80);
			}
			j++;
		} 
		String tt = new String(bt2);
		return tt; 
	}

 注意:上例在实际编程中效果很好,只是存储的中文信息需要经过同样处理,才能被其他系统使用。而且如果中文字串出现英文字符,实际上增加了额外的存储空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值