Java 按字节截取字符串

package io.p7.encoding;

import java.io.UnsupportedEncodingException;

public class Test {

	/*
	 * 在java中 字符串“abcd”与字符串"ab你好"长度是一样的 都是四个字符
	 * 但对应的字节数不同  一个汉子占两个字节
	 * 定义一个方法按照最大的字节数来取子串
	 * 如:对于“ab你好”,如果取三个字节 那么字串就是ab与 “你”字的半个
	 * 那 半个就要舍弃 如果取四个字节就是 “ab你” 取五个字节就是"ab你"加“好”半个
	 */
	public static void main(String[] args) throws UnsupportedEncodingException { 
		String str="ab你好cd谢谢";
/*		int len=str.getBytes("gbk").length;
		for(int x=0;x<len;x++) {
			System.out.println("截取"+(x+1)+"个字节结果为:"+curStringByByte(str, x+1));*/
			
			
		int len=str.getBytes("utf-8").length;
		for(int x=0;x<len;x++) {
			System.out.println("截取"+(x+1)+"个字节结果为:"+curStringByU8Byte(str, x+1));	
		}
		
	}
	private static String curStringByU8Byte(String str, int len) throws UnsupportedEncodingException {
		byte []buf=str.getBytes("utf-8");
		
		int count=0;
		for(int x=len-1;x>=0;x--) {
			if(buf[x]<0)
				count++;
			else
				break;
		}
		if(count%3==0)
			return new String(buf,0,len,"utf-8");
		else if(count%3==1)
			return new String(buf, 0, len-1,"utf-8");
		else
			return new String(buf,0,len-2,"utf-8");
		
	}
	public static String curStringByByte(String str,int len) throws UnsupportedEncodingException {
	
		byte []buf=str.getBytes("gbk");
		
		int count=0;
		for(int x=len-1;x>=0;x--) {
			if(buf[x]<0)
				count++;
			else
				break;
		}
		if(count%2==0)
			return new String(buf,0,len,"gbk");
		else 
			return new String(buf, 0, len,"gbk");
		
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值