【Java】编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
public class KartString {
public static String bSubstring(String s, int length) throws Exception {
byte[] bytes = s.getBytes("Unicode");
int n = 0;
int i = 2;
for (; i < bytes.length && n < length; i++) {
if (i % 2 == 1) {
} else {
if (bytes[i] != 0) {
n++;
}
}}
if (i % 2 == 1)
{
if (bytes[i - 1] != 0)
i = i - 1;
else
i = i + 1;
}
return new String(bytes, 0, i, "Unicode");}
public static void main(String[] args) throws Exception {
String str = "我AFSD是KJHJKSD人呢SKJS";
KartString ks = new KartString();
String la = ks.bSubstring(str, 10);
System.out.println(la);
}
}