汉字占多个字节,若按指定字节长度截取字符串,如何处理1/3个汉字?

截取字符串的函数 按照字节

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

分析

不能使用substring(beginIndex, endIndex),因为它 是返回的字符,题目要求的是字节

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

UTF- 8 和 GBK

UTF- 8是用以解决国际上字符的一种多字节编码,它对英文使用8位(即一个字节),中文使用24为(三个字节)来编码。

GBK是国家标准GB2312基础上扩容后兼容GB2312的标准。GBK的文字编码是用双字节来表示的,即不论中、英文字符均使用双字节来表示。

String x = "我";
System.out.println(x.getBytes("utf-8").length);
System.out.println(x.getBytes("GBK").length);
/**
 * 输出
 * 3
 * 2
 */
String s = "我ABC汗";
System.out.println(new String(s.getBytes("GBK"), "GBK"));
输出"我ABC汗"

System.out.println(new String(s.getBytes(), "GBK"));
乱码 鎴慉BC姹�

System.out.println(new String(s.getBytes(), "utf8"));
输出"我ABC汗" 

System.out.println(new String(s.getBytes("utf8"), "utf8"));
输出"我ABC汗"  

System.out.println(new String(s.getBytes(), "ascii"));
���ABC���
可以看出默认使用 utf8 编码,然后 ascii 解码,英文正常,但是汉字是3个

分析
默认是utf8编码,所以不写没事。encode 和 decode 需要相同
记住 jvm 里面是 unicode,出来时候才会具体编码

解决方法

思路就是从 String 的每个字符 遍历,然后如果是中文的,就-2,如果是英文的,-1。
String.valueOf(b[i]).getBytes().length > 1判断是否是中文

static String split(String orignal, int 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值