美文网首页
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节

作者: bug_华 | 来源:发表于2017-09-29 10:10 被阅读0次

首先要了解中文字符有多种编码及各种编码的特征。假设n为要截取的字节数。

public static void main(String[] args) throws Exception{
    String str ="我a爱中华abc我爱def';
    int num =trimGBK(str.getBytes("GBK"),6);
    System.out.println(str.substring(0,num));
 }
public static int trimGBK(byte[] buf,int n){
    int num = 0;
    boolean bChineseFirstHalf = false;
    for(int i=0;i<n;i++){
        if(buf[i]<0&& !bChineseFirstHalf){    //Byte的范围是-127-128,一个汉子占两个Byte且Byte[i]<0
          bChineseFirstHalf= true;  // 
        }else{
          num++;  //1    2   3 
          bChineseFirstHalf= false;
        }
    }
    return num;
}
image.png

相关文章

网友评论

      本文标题:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节

      本文链接:https://www.haomeiwen.com/subject/ionbextx.html