在 Java 中,如果我有一个字符串 x
,我如何计算该字符串中的字节数?
最佳答案
字符串是字符(即代码点)的列表。用于表示字符串的字节数完全取决于您使用哪种编码将其转换为字节。
也就是说,你可以把字符串转成字节数组,然后看它的大小如下:
// The input string for this test
final String string = "Hello World";
// Check length, in characters
System.out.println(string.length()); // prints "11"
// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"
final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"
final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"
final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"
final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"
所以你看,即使是一个简单的“ASCII”字符串在其表示中也可以有不同数量的字节,这取决于所使用的编码。使用您对案例感兴趣的任何字符集作为 getBytes()
的参数。并且不要陷入假设 UTF-8 将 每个 字符表示为单个字节的陷阱,因为这也不正确:
final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms
// Check length, in characters
System.out.println(interesting.length()); // prints "4"
// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"
final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"
final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"
final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")
final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")
(请注意,如果您不提供字符集参数,则会使用平台的默认字符集。这在某些情况下可能很有用,但通常您应该避免依赖默认值,并且在需要编码/解码时始终使用显式字符集。)
关于java - Java中字符串的字节数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4385623/