截取包含中文的字符串(处理字符串和字节数)
import java.io.UnsupportedEncodingException;
public class SplictString {
public static void main(String[] args) throws Exception {
String string = "我a爱中华abc我爱acm";
int num = trimGBK(string.getBytes("GBK"), 5);
System.out.println(string.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) {
bChineseFirstHalf = true;
}else {
num++;
bChineseFirstHalf = false;
}
}
return num;
}
}