package demo;
import java.io.UnsupportedEncodingException;
/**
* @author hx
*编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。
*但是要保证汉字不被截半个,如“我ABC”4,应该截为“我AB”,
*输入“我ABC汉DEF”,6,应该输出为“我ABC”而不是“我ABC+汉的半个”。
*/
public class 按字节截取字符串 {
public static String subStringAsByte(String s, int n) {
String result = "";
//将字符串转换成指定编码方式的byte数组的函数
byte b[] = null;
try {
b = s.getBytes("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int count = 0;//记录选取部分中汉字字节(负数)个数
if (n >= 1) {
if(n>b.length)//超出字符串长度 输出源字符串
return s;
for(int i=0; i<n; i++){
if(b[i]<0)
count++;
}
if (count%2!=0)//如果存在半个汉字,则舍去
result = new String(b, 0, n - 1);
else
result = new String(b, 0, n);
}
return result;
}
public static void main(String[] args) {
String s = "我abc汉族的人efg";
System.out.println(subStringAsByte(s, 8));
}
}