输入“我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); } }