/**
题目:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,
输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*/
public static void stringSplit(String str, int len) {
if(null == str) {
return;
}
if(len > str.length()) {
len = str.length();
}
// 将string转换成byte数组
byte[] bt = str.getBytes();
//对是否出现截半做分类处理,如果出现了截半情况,则asc码值小于0
if(bt[len]<0) {
String result = new String(bt,0,len--);
System.out.println("出现了截半情况,结果为:" + result);
} else {
String result = new String(bt,0,len);
System.out.println("没有出现截半情况,结果为:" + result);
}
}
public static void main(String args[]) {
stringSplit("我ABC",4)
}
注:utf-8情况下,汉字占3个字节,这里的代码统一按汉字占2个字节编码