您的位置:首页 > 其它

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个。

2016-06-26 17:19 543 查看
public class TestSplitString {
public static String splitString(String str,int byteNum) throws Exception {
char[] c = str.toCharArray();
System.out.println(Arrays.toString(c));
return new String(c,0,getToIndex(c, byteNum));
}
public static int getToIndex(char[] c,int byteNum) throws Exception{
int num = 0;
for(int i = 0;i < c.length;i++){
num += ((c[i] + "").getBytes("gb2312")).length;
if(num >= byteNum)
return i + 1;
if(i + 1 == c.length) 
return c.length;
}
return 0;
}
public static void main(String[] args) throws Exception {
System.out.println(splitString("我ABC们DEF",9));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class string 函数