40

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

4

7 回答 7

29

这是一个简单的循环,它计算 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;
}

确实处理出现在输入字符串中的代理对。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);

}

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

于 2008-09-23T07:30:27.123 回答
26

您应该使用CharsetEncoder,尽可能多的简单getBytes()+ 复制可以将 UTF-8 字符减半。

像这样的东西:

public static int truncateUtf8(String input, byte[] output) {
    
    ByteBuffer outBuf = ByteBuffer.wrap(output);
    CharBuffer inBuf = CharBuffer.wrap(input.toCharArray());

    CharsetEncoder utf8Enc = StandardCharsets.UTF_8.newEncoder();
    utf8Enc.encode(inBuf, outBuf, true);
    System.out.println("encoded " + inBuf.position() + " chars of " + input.length() + ", result: " + outBuf.position() + " bytes");
    return outBuf.position();
}
于 2008-09-23T06:11:47.673 回答
19

这是我想出的,它使用标准的 Java API,因此应该是安全的,并且与所有 unicode 怪异和代理对等兼容。解决方案取自http://www.jroller.com/holy/entry/truncating_utf_string_to_the并带有检查添加用于 null 并在字符串的字节数少于maxBytes时避免解码。

/**
 * Truncates a string to the number of characters that fit in X bytes avoiding multi byte characters being cut in
 * half at the cut off point. Also handles surrogate pairs where 2 characters in the string is actually one literal
 * character.
 *
 * Based on: http://www.jroller.com/holy/entry/truncating_utf_string_to_the
 */
public static String truncateToFitUtf8ByteLength(String s, int maxBytes) {
    if (s == null) {
        return null;
    }
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    byte[] sba = s.getBytes(charset);
    if (sba.length <= maxBytes) {
        return s;
    }
    // Ensure truncation by having byte buffer = maxBytes
    ByteBuffer bb = ByteBuffer.wrap(sba, 0, maxBytes);
    CharBuffer cb = CharBuffer.allocate(maxBytes);
    // Ignore an incomplete character
    decoder.onMalformedInput(CodingErrorAction.IGNORE)
    decoder.decode(bb, cb, true);
    decoder.flush(cb);
    return new String(cb.array(), 0, cb.position());
}
于 2016-02-02T09:04:03.730 回答
10

UTF-8 编码有一个简洁的特性,可以让您查看您在字节集中的位置。

在您想要的字符限制处检查流。

  • 如果它的高位为0,它是一个单字节字符,只需将它替换为0就可以了。
  • 如果它的高位是 1,下一位也是,那么你是在一个多字节字符的开头,所以只需将该字节设置为 0 就可以了。
  • 如果高位为 1 但下一位为 0,那么您在一个字符的中间,沿着缓冲区返回,直到遇到高位中有 2 个或更多 1 的字节,然后将该字节替换为0。

示例:如果您的流是:31 33 31 C1 A3 32 33 00,您可以使字符串长度为 1、2、3、5、6 或 7 个字节,但不能为 4,因为这会将 0 放在 C1 之后,这是多字节字符的开始。

于 2008-09-23T06:07:41.160 回答
7

你可以使用 -new String(data.getBytes("UTF-8") , 0, maxLen, "UTF-8");

于 2018-10-24T06:53:13.290 回答
3

您可以在不进行任何转换的情况下计算字节数。

foreach character in the Java string
  if 0 <= character <= 0x7f
     count += 1
  else if 0x80 <= character <= 0x7ff
     count += 2
  else if 0x800 <= character <= 0xd7ff // excluding the surrogate area
     count += 3
  else if 0xdc00 <= character <= 0xffff
     count += 3
  else { // surrogate, a bit more complicated
     count += 4
     skip one extra character in the input stream
  }

您必须检测代理对(D800-DBFF 和 U+DC00–U+DFFF)并为每个有效代理对计算 4 个字节。如果你得到第一个范围内的第一个值,第二个范围内的第二个值,一切正常,跳过它们并加 4。但如果没有,那么它是一个无效的代理对。我不确定 Java 是如何处理这个问题的,但是在那种(不太可能的)情况下,你的算法必须正确计算。

于 2008-09-23T07:47:41.373 回答
0

根据billjamesdev 的回答,我提出了以下方法,据我所知,这是最简单的方法,并且仍然适用于代理对:

public static String utf8ByteTrim(String s, int size) {
    final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
    if ((bytes[size-1] & 0x80) != 0) { // inside a multibyte sequence
        while ((bytes[trimSize-1] & 0x40) == 0) { // 2nd, 3rd, 4th bytes
            trimSize--;
        }
        trimSize--;
    }
    return new String(bytes, 0, size, StandardCharsets.UTF_8);
}

一些测试:

String test = "Aæ尝试";
IntStream.range(1, 16).forEachOrdered(i ->
        System.out.println("Size " + i + ": " + utf8ByteTrim(test, i))
);

---

Size 1: A
Size 2: A
Size 3: A
Size 4: Aæ
Size 5: Aæ
Size 6: Aæ
Size 7: Aæ
Size 8: Aæ
Size 9: Aæ
Size 10: Aæ
Size 11: Aæ尝
Size 12: Aæ尝
Size 13: Aæ尝试
Size 14: Aæ尝试
Size 15: Aæ尝试
于 2021-12-13T17:46:18.900 回答