標籤:style blog http 2014 問題 for
解決問題之前,我們需要瞭解的是,在GBK字元集的編碼中漢字佔2個位元組,字母和其他字元佔一個位元組,而在utf-8中漢字佔3,或者4個位元組,字母佔2個位元組,由於,utf一下佔2個3個位元組,一下佔4個位元組,不好拆分出指定的漢字加字母,所以才用gbk的編碼格式,漢字佔2個位元組,字母一個位元組。
在把漢字轉換成位元組的時候,輸出的位元組的值小於0,字母轉換成位元組的時候,輸出的值就是其對應的數字。
在String對象中,它的長度計算,是漢字算一個,字母也算一個
代碼如下:
package com.wj.demo1;
public class SplitChinese {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
String st1="我a愛中華abc我愛傳智def";
String st2="a我ABC漢a";//定義的測試字串
String st3="ac23好11";
System.out.println("str is "+st2.length());//不管是否是漢字,都只佔用一個位元組,得到字串的長度
int num=trimGBK(st2.getBytes("GBK"),2);//得到應該截取的長度
System.out.println(st2.substring(0, num));//輸出指定的截取長度
}
public static int trimGBK(byte[] buf,int n){
int num=0;//標誌變數,截取的長度
boolean bChineseFirstHalf=false;//標誌是否出現漢字
System.out.println("the buf size is :"+buf.length);
for(int i=0;i<n;i++){
System.out.println("byte[i]="+buf[i]);//列印對應的位元組的值
if(buf[i]<0&&!bChineseFirstHalf){//如果buf[i]<0則為漢字,如果是首次出現的漢字位元組則設定為true
bChineseFirstHalf=true;//2個位元組的漢字首,出現的漢字位元組
}else{
num++;//累加,記錄應該截取的長度
bChineseFirstHalf=false;
}
}
return num;//返回截取的長度
}
}
當int num=trimGBK(st2.getBytes("GBK"),2);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
a
當int num=trimGBK(st2.getBytes("GBK"),1);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
a
當int num=trimGBK(st2.getBytes("GBK"),3);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
a我
當int num=trimGBK(st2.getBytes("GBK"),4);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
byte[i]=65
a我A
當int num=trimGBK(st2.getBytes("GBK"),6);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
byte[i]=65
byte[i]=66
byte[i]=67
a我ABC
當int num=trimGBK(st2.getBytes("GBK"),7);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
byte[i]=65
byte[i]=66
byte[i]=67
byte[i]=-70
a我ABC
當int num=trimGBK(st2.getBytes("GBK"),8);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
byte[i]=65
byte[i]=66
byte[i]=67
byte[i]=-70
byte[i]=-70
a我ABC漢
當int num=trimGBK(st2.getBytes("GBK"),9);/的時候輸出為
str is 7
the buf size is :9
byte[i]=97
byte[i]=-50
byte[i]=-46
byte[i]=65
byte[i]=66
byte[i]=67
byte[i]=-70
byte[i]=-70
byte[i]=97
a我ABC漢a