编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个。
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));
}
}
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));
}
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。