关于java按字节截取含有汉字的字符串的解法

关于java按字节截取带有汉字的字符串的解法
转自:http://lanxia39.iteye.com/blog/190439
编程:编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。 但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。

public class parseCH{

public void splitIt(String splitStr, int bytes) {
int cutLength = 0;
int byteNum = bytes;
byte bt[] = splitStr.getBytes();
System.out.println("Length of this String ===>" + bt.length);
if (bytes > 1) {
for (int i = 0; i < byteNum; i++) {
if (bt[i] < 0) {
cutLength++;

}
}

if (cutLength % 2 == 0) {
cutLength /= 2;
}else
{
cutLength=0;
}
}
int result=cutLength+--byteNum;
if(result>bytes)
{
result=bytes;
}
if (bytes == 1) {
if (bt[0] < 0) {
result+=2;

}else
{
result+=1;
}
}
String substrx = new String(bt, 0, result);
System.out.println(substrx);

}

public static void main(String args[]) {
String str = "我abc的DEFe呀fgsdfg大撒旦";
int num =1;
System.out.println("num:" + num);
parseCH sptstr = new parseCH();
sptstr.splitIt(str, num);
}

}
转自:http://lanxia39.iteye.com/blog/190439