首先要了解中文字符有多種編碼及各種編碼的特征鹅颊。假設(shè)n為要截取的字節(jié)數(shù)敷存。
public static void main(String[] args) throws Exception{
String str ="我a愛(ài)中華abc我愛(ài)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,一個(gè)漢子占兩個(gè)Byte且Byte[i]<0
bChineseFirstHalf= true; //
}else{
num++; //1 2 3
bChineseFirstHalf= false;
}
}
return num;
}
image.png