获取字符串的长度
为了获得 String 对象的长度,请在其上调用 length() 方法。长度等于字符串中 UTF-16 代码单元(字符)的数量。
String str = "Hello, World!";
System.out.println(str.length()); // Prints out 13
String 中的 char 是 UTF-16 值。值≥0x1000 的 Unicode 代码点(例如,大多数表情符号)使用两个 char 位置。要计算 String 中 Unicode 代码点的数量,无论每个代码点是否符合 UTF-16 char 值,你都可以使用 codePointCount 方法:
int length = str.codePointCount(0, str.length());
从 Java 8 开始,你还可以使用代码点流:
int length = str.codePoints().count();