在Java中,如果我有一个字符串x,我如何计算该字符串中的字节数?


当前回答

要避免try catch,请使用:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
System.out.println(b.length);

其他回答

根据如何在Java中转换字符串和UTF8字节数组:

String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);

要避免try catch,请使用:

String s = "some text here";
byte[] b = s.getBytes(StandardCharsets.UTF_8);
System.out.println(b.length);

有一个叫做getBytes()的方法。明智地使用它。

尝试使用apache commons:

String src = "Hello"; //This will work with any serialisable object
System.out.println(
            "Object Size:" + SerializationUtils.serialize((Serializable) src).length)

String实例在内存中分配一定数量的字节。也许您正在查看类似sizeof(“Hello World”)的东西,它将返回数据结构本身分配的字节数。

In Java, there's usually no need for a sizeof function, because we never allocate memory to store a data structure. We can have a look at the String.java file for a rough estimation, and we see some 'int', some references and a char[]. The Java language specification defines, that a char ranges from 0 to 65535, so two bytes are sufficient to keep a single char in memory. But a JVM does not have to store one char in 2 bytes, it only has to guarantee, that the implementation of char can hold values of the defines range.

sizeof在Java中没有任何意义。但是,假设我们有一个大的String并且一个char分配两个字节,那么String对象的内存占用至少是2 * str.length()字节。