这个题目出自java程序员面试宝典,我看了半天觉得代码有点小问题,做了点小修改,同时觉得这个题目蛮有意思,在此贴出来给大家讨论下:
描述: 编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串。但是要保证汉字不被截取半个,如”我 ABC”,4“,应该截为“我 AB”,输入"“我 ABC 汉 DEF”,6",应该输出为“我 ABC”,而不是半个“我 ABC +汉的半个汉字”。(某公司面试题)
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class TestString {
public static void main(String[] args) throws IOException {
String s1 = "3我 ABC 是 chinese";
String s2 = "中 ";
int count = 9;
char c;
String original = new String(s1.getBytes("gbk"),"gbk");
System.out.println(original);
StringBuffer sb = new StringBuffer("");
if(s1 != null && !s1.equals("")){
if(count > 0 && count < original.length()){
for(int i = 0; i < count ; i++){
c = original.charAt(i);
// System.out.println("c:"+c);
if(String.valueOf(c).getBytes().length > 1){
--count;
if(i < count){
sb.append(c);
}
}
else{
sb.append(c);
}
}
}
}
System.out.println(sb.toString());
System.out.println(sb.toString().length());
}
}
结果为:
3我 ABC 是 chinese
3我 ABC
7
在这里重要的是要判断字符c是否为汉字,汉字与非汉字字符的字节数目是不同,但是如果 String s1 = "中";和String s2 = "f";s1.length() = s2.length() = 1;但是s1.getBytes().length = 2; s2.getBytes().length = 1;是否为汉字通过这里来区别,当碰到汉字时,我们就让字节总数减1处理,当没有超过总数count时,我们添加到StringBuffer中。