java - 一旦 UTF-8 编码,如何截断 java 字符串以适应给定的字节数?

标签 java string unicode utf-8 truncate

如何截断 java String 以便我知道它在 UTF-8 编码后将适合给定数量的字节存储?

最佳答案

这是一个简单的循环,用于计算 UTF-8 表示的大小,并在超出时截断:

public static String truncateWhenUTF8(String s, int maxBytes) {
    int b = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);

        // ranges from http://en.wikipedia.org/wiki/UTF-8
        int skip = 0;
        int more;
        if (c <= 0x007f) {
            more = 1;
        }
        else if (c <= 0x07FF) {
            more = 2;
        } else if (c <= 0xd7ff) {
            more = 3;
        } else if (c <= 0xDFFF) {
            // surrogate area, consume next char as well
            more = 4;
            skip = 1;
        } else {
            more = 3;
        }

        if (b + more > maxBytes) {
            return s.substring(0, i);
        }
        b += more;
        i += skip;
    }
    return s;
}

这个确实处理surrogate pairs出现在输入字符串中。 Java 的 UTF-8 编码器(正确)将代理对输出为单个 4 字节序列而不是两个 3 字节序列,因此 truncateWhenUTF8() 将返回它可以返回的最长截断字符串。如果您在实现中忽略代理对,则截断的字符串可能会比它们需要的短。

我没有对该代码进行大量测试,但这里有一些初步测试:

private static void test(String s, int maxBytes, int expectedBytes) {
    String result = truncateWhenUTF8(s, maxBytes);
    byte[] utf8 = result.getBytes(Charset.forName("UTF-8"));
    if (utf8.length > maxBytes) {
        System.out.println("BAD: our truncation of " + s + " was too big");
    }
    if (utf8.length != expectedBytes) {
        System.out.println("BAD: expected " + expectedBytes + " got " + utf8.length);
    }
    System.out.println(s + " truncated to " + result);
}

public static void main(String[] args) {
    test("abcd", 0, 0);
    test("abcd", 1, 1);
    test("abcd", 2, 2);
    test("abcd", 3, 3);
    test("abcd", 4, 4);
    test("abcd", 5, 4);

    test("a\u0080b", 0, 0);
    test("a\u0080b", 1, 1);
    test("a\u0080b", 2, 1);
    test("a\u0080b", 3, 3);
    test("a\u0080b", 4, 4);
    test("a\u0080b", 5, 4);

    test("a\u0800b", 0, 0);
    test("a\u0800b", 1, 1);
    test("a\u0800b", 2, 1);
    test("a\u0800b", 3, 1);
    test("a\u0800b", 4, 4);
    test("a\u0800b", 5, 5);
    test("a\u0800b", 6, 5);

    // surrogate pairs
    test("\uD834\uDD1E", 0, 0);
    test("\uD834\uDD1E", 1, 0);
    test("\uD834\uDD1E", 2, 0);
    test("\uD834\uDD1E", 3, 0);
    test("\uD834\uDD1E", 4, 4);
    test("\uD834\uDD1E", 5, 4);

}

更新修改后的代码示例,现在处理代理对。

关于java - 一旦 UTF-8 编码,如何截断 java 字符串以适应给定的字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/119328/

相关文章:

python - 获取 url 时出现 UnicodeEncodeError

python - 如何在 Tkinter 菜单中获取 Mac "command"符号

java - 尝试在对话框中使 ImageView 全尺寸不起作用

java - 可以不使用定时器

java - 将不同类类型的对象作为 java 中映射中的值进行处理

python - 通过位置列表将字符串中的字符替换为另一个字符

java - 读取和替换字符串中的整数

java - 在抽屉导航中更改特定菜单项的文本大小

python - 为什么Python在这里打印大括号?

html - 使用 attr(data-icon) 属性在元素之前显示 unicode