按照字节长度截取string:
记录一下
public class Stri {
public static void main(String args[]) throws UnsupportedEncodingException {
String sr="我a中guo号";
//中文字节长度 gbk 2 utf-8 3
byte [] be=sr.getBytes("gbk");
System.out.println(getStrIndex(be,10));
System.out.println(new String(be, 0, getStrIndex(be,10),"gbk"));
}
public static int getStrIndex(byte [] be,int i){
//截取字节长度必须小于字符串字节长度
if(i<be.length) {
//asi小于0 则递归
if (be[i] < 0) {
i--;
if (i > 0) {
getStrIndex(be, i);
}
}
}
return i;
}
}
本文介绍了一种按指定字节长度截取GBK编码的字符串的方法,通过递归函数getStrIndex()确定截取位置,再利用getBytes()和new String()实现截取。示例代码展示了如何在Java中处理中文字符的字节长度问题。
1482

被折叠的 条评论
为什么被折叠?



