经过 UTF-8 编码后,如何截断 Java 字符串以适合给定的字节数?

问题描述 投票:0回答:8

如何截断 java

String
,以便我知道它在 UTF-8 编码后适合给定数量的字节存储?

java string unicode utf-8 truncate
8个回答
35
投票

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

}

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


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();
}

25
投票

这是我的想法,它使用标准 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());
}

10
投票

UTF-8 编码有一个巧妙的特征,可以让您看到自己在字节集中的位置。

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

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

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


8
投票

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


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 如何处理这个问题,但你的算法必须在这种(不太可能)的情况下进行正确的计数。


0
投票

从字符串尾部扫描比从头开始扫描效率更高,尤其是在很长的字符串上。所以 walen 走在正确的道路上,不幸的是,这个答案没有提供正确的截断。

如果您想要一个仅向后扫描几个字符的解决方案,这是最好的选择。

使用 billjamesdev 的答案中的数据,我们可以有效地向后扫描并正确获取字符边界上的截断。

public static String utf8ByteTrim(String s, int requestedTrimSize) {
    final byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
    int maxTrimSize = Integer.min(requestedTrimSize, bytes.length);
    int trimSize = maxTrimSize;
    if ((bytes[trimSize-1] & 0x80) != 0) { // inside a multibyte sequence
        while ((bytes[trimSize - 1] & 0x40) == 0) { // 2nd, 3rd, 4th bytes
            trimSize--;
        }
        trimSize--;  // Get to the start of the UTF-8
        // Now see if that final UTF-8 character fits.
        // Assume the UTF-8 starts with binary 110xxxxx and is 2 bytes
        int numBytes = 2;  
        if ((bytes[trimSize] & 0xF0) == 0xE0) {
            // If the UTF-8 starts with binary 1110xxxx it is 3 bytes
            numBytes = 3;
        } else if ((bytes[trimSize] & 0xF8) == 0xF0) {
            // If the UTF-8 starts with binary 11110xxx it is 3 bytes
            numBytes = 4;
        }
        if( (trimSize + numBytes) == maxTrimSize)  {
            // The entire last UTF-8 character fits
            trimSize = maxTrimSize; 
        }
    }
    return new String(bytes, 0, trimSize, StandardCharsets.UTF_8);
}

只有一个 while 循环在向后走时最多执行 3 次迭代。然后一些 if 语句将确定要截断哪个字符。

一些测试:

String test = "Aæ😂尝试"; // Sizes: (1,2,4,3,3) = 13 bytes
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æ😂尝试

0
投票

基于 billjamesdev 的回答我想出了以下方法,据我所知,这是最简单的并且对于代理对仍然可以正常工作:

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

一些测试:

String test = "Aæ😂尝试";
IntStream.range(1, 20).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æ😂尝试
Size 16: Aæ😂尝试
Size 17: Aæ😂尝试
Size 18: Aæ😂尝试
Size 19: Aæ😂尝试

编辑:我的代码存在问题,因为我假设输入

trimSize
始终低于输入字符串的实际字节长度(因为否则就没有任何内容可以“修剪”)。
如果
trimSize
实际上大于
bytes.length
(因此最后一个字符也适合),正确返回整个字符串所需的唯一更改是检查
if
中的条件,然后在创建时使用适当的大小新字符串。
无需添加 10 多行条件语句。

© www.soinside.com 2019 - 2024. All rights reserved.