栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java中字符串的字节数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java中字符串的字节数

字符串是字符列表(即代码点)。表示字符串所用的字节数完全取决于你使用哪种编码将其转换为字节。

也就是说,你可以将字符串转换为字节数组,然后按如下所示查看其大小:

// The input string for this testfinal String string = "Hello World";// Check length, in charactersSystem.out.println(string.length()); // prints "11"// Check enpred sizesfinal 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 = "uF93DuF936uF949uF942"; // Chinese ideograms// Check length, in charactersSystem.out.println(interesting.length()); // prints "4"// Check enpred sizesfinal 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 enpred "????")final byte[] winBytes = interesting.getBytes("CP1252");System.out.println(winBytes.length); // prints "4" (probably enpred "????")

(请注意,如果不提供字符集参数,则会使用平台的默认字符集。这在某些情况下可能很有用,但是通常应避免依赖默认值,并且在编码/时始终使用显式字符集需要解码。)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456500.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号