编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个,如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”。

程序字符串浏览:186收藏:1
答案:
import java.io.IOException;
public class AnswerB03 {
    public static void main(String[] args) throws IOException {
        String s = "我ABC汉DEF";
        System.out.println(substring(s, 6));
    }
    public static String substring(String s, int length) {
        char[] cs = s.toCharArray();
        StringBuilder builder = new StringBuilder();
        int count = 0;
        for (char c : cs) {
            if (isAsc(c)) {
                count++;
            } else {
                count += 2;
            }
            if (count > length) {
                break;
            }
            builder.append(c);
        }
        return builder.toString();
    }
    public static boolean isAsc(char c) {
        return c < 128;
    }
}