import java.io.UnsupportedEncodingException;



public class SubString {

//编写一个截取字符串的函数,输入为一个字符串和字节

//数,输出为按字节截取的字符串,但要保证汉字不被截取半

//个,如“我 ABC”,4,应该截取“我 AB”,输入“我 ABC

//汉 DEF”,6,应该输出“我 ABC”,而不是“我 ABC+汉的半个”。

//思想:首先要了解中文字符有多种编码及各种编码的特征。假设n 为要截取的字节数。

//汉字在GBK中占用两个字节,每个字节返回的是负数。

public static void main(String[] args) throws Exception {

String str="我不a会";

int num = trimGBK(str.getBytes("GBK"),4);

System.out.println(str.substring(0, num));

}

public static int trimGBK(byte[]buf,int n){

int num=0;

boolean ishalfchinese=false;

for(int i=0;i<n;i++){

if(buf[i]<0&&!(ishalfchinese)){

ishalfchinese=true;

}

else{

num++;

ishalfchinese=false;

}

}

return num;

}

}