算法之截取帶漢字的字符串
阿新 • • 發佈:2017-07-02
throw int 輸入 應該 subst return bstr get 字符串
輸入“我ABC漢DEF”和字節數6,應該輸出“我ABC”,而不是“我ABC+漢的半個”。
public class CutOutHanzi { public static void main(String[] args) throws UnsupportedEncodingException { String str = "我ABC漢DEF"; cutOutGBK(str,6); } public static String cutOutGBK(String str,int n) throws UnsupportedEncodingException{//n為要截取的字節數 byte[] buf = str.getBytes("GBK"); int num = 0; boolean isHanziFirstHalf = false; for (int i = 0; i < n; i++) { if(buf[i]<0 && !isHanziFirstHalf) isHanziFirstHalf = true; else{ num++; isHanziFirstHalf= false; } } return str.substring(0,num); } }
算法之截取帶漢字的字符串