编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“小弟我ABC”4,应该截为“小弟我AB”,输入“小弟我ABC汉
编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉
// 我的想法是如果截取字符串的位置是半个中文字符的话 那我就多截取一个字节(可能会抛出异常)
// 如果两个字符串的长度相等说明该位置是半个中文字符应该去掉
public String split(String str, int bytes) {
String result = "";
if (str == null || "".equals(str) || bytes < 1) {
return "";
}
if (bytes > str.getBytes().length) {
return str;
}
if (bytes >= 1) {
result = new String(str.getBytes(), 0, bytes);
try {
//这里很有可能跑出异常抛出异常说明截取的位置不是半个中文字符异常可以忽略
String temp = new String(str.getBytes(), 0, bytes + 1);
if (result.length() == temp.length()) {
result = result.substring(0, result.length() - 1);
}
} catch (Exception e) {
}
}
return result;
}
本文为原创 转载请注明原作者
// 我的想法是如果截取字符串的位置是半个中文字符的话 那我就多截取一个字节(可能会抛出异常)
// 如果两个字符串的长度相等说明该位置是半个中文字符应该去掉
public String split(String str, int bytes) {
String result = "";
if (str == null || "".equals(str) || bytes < 1) {
return "";
}
if (bytes > str.getBytes().length) {
return str;
}
if (bytes >= 1) {
result = new String(str.getBytes(), 0, bytes);
try {
//这里很有可能跑出异常抛出异常说明截取的位置不是半个中文字符异常可以忽略
String temp = new String(str.getBytes(), 0, bytes + 1);
if (result.length() == temp.length()) {
result = result.substring(0, result.length() - 1);
}
} catch (Exception e) {
}
}
return result;
}
本文为原创 转载请注明原作者