编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如"我ABC"4,应该截为"我AB",输入"我ABC汉DEF",6,应该输出为"我ABC"而不是"我ABC+汉的半个"
package com.sing.demo;
class SplitString {
public static void main(String[] args) {
String str = "Atet中dd文dsaf中男大344";
split(str, 9);
}
public static void split(String str, int byteleng) {
byte[] bt = str.getBytes();
byte[] temp;
int leng;
if (bt[byteleng - 1] < 0 && bt[byteleng - 2] > 0) {
leng = byteleng - 1;
} else {
leng = byteleng;
}
temp = new byte[leng];
for (int i = 0; i < temp.length; i++) {
// System.out.println(bt[i]);
temp[i] = bt[i];
}
System.out.println(new String(temp));
}
}