如何實現按位元組擷取字串(中文佔2位元組,英文佔1位元組,substring())?
阿新 • • 發佈:2019-02-07
str = "我a智慧abc"
substring(str, 5) 會擷取成為 “我a智慧a”
現在要實現中文佔2位元組,英文佔1位元組,按位元組擷取 ,輸出應該為"我a智"
public class SubString{ /** * */ 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){ //是中文的情況,num不用++ bChineseFirstHalf = true; }else{ num++; bChineseFirstHalf = false; } } return num; } public static void main(String[] args){ String str = "我a智慧abc"; try{ //使用給定的 charset 將此 String 編碼到 byte 序列,並將結果儲存到新的 byte 陣列。 int num = trimGBK(str.getBytes("GBK"),5); System.out.println(str.substring(0,num)); //輸出"我a智" }catch(Exception e){ e.printStackTrace(); } //System.out.println(str.substring(0,5)); //輸出"我a智慧a" } } /* String str = "我a智慧abc"; for(int i=0; i<str.getBytes("GBK").length; i++){ System.out.println(str.getBytes("GBK")[i]); } 輸出:-50 -46 97 -42 -57 - 60 -36 97 98 99 中文是兩個負數,英文是1個正數 */