String
Javaが UTF-8 でエンコードされると、特定のバイト数のストレージに収まるようにJava を切り詰めるにはどうすればよいですか?
7 に答える
以下は、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 エンコーダーは (正しく) サロゲート ペアを 2 つの 3 バイト シーケンスではなく 1 つの 4 バイト シーケンスとして出力するため、可能な限り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);
}
更新変更されたコード例。サロゲート ペアを処理するようになりました。
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();
}
これが私が思いついたものです。標準のJava APIを使用しているため、すべてのユニコードの奇妙さとサロゲートペアなどと安全で互換性があるはずです。 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());
}
UTF-8 エンコーディングには、バイトセットのどこにいるかを確認できる優れた特性があります。
必要な文字数制限でストリームを確認してください。
- 上位ビットが 0 の場合、それは 1 バイトの char です。それを 0 に置き換えるだけで問題ありません。
- その上位ビットが 1 で、次のビットも同じである場合、マルチバイト文字の先頭にいるので、そのバイトを 0 に設定するだけで問題ありません。
- 上位ビットが 1 で次のビットが 0 の場合は、文字の途中にあり、上位ビットに 2 つ以上の 1 があるバイトにヒットするまでバッファーに沿って戻り、そのバイトを0.
例: ストリームが 31 33 31 C1 A3 32 33 00 の場合、文字列の長さを 1、2、3、5、6、または 7 バイトにすることができますが、4 バイトにすることはできません。マルチバイト文字の開始です。
変換を行わずにバイト数を計算できます。
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 バイトをカウントする必要があります。最初の範囲で最初の値を取得し、2 番目の範囲で 2 番目の値を取得した場合は、すべて問題ありません。それらをスキップして 4 を追加します。そうでない場合は、無効なサロゲート ペアです。Javaがそれをどのように処理するかはわかりませんが、アルゴリズムはその(可能性は低い)ケースで正しいカウントを行う必要があります.