Java获取字符串的长度

示例

为了获得String对象的长度,请对其调用length()方法。长度等于字符串中UTF-16代码单元(字符)的数量。

String str = "Hello, World!";
System.out.println(str.length()); // 打印出13

Ideone现场演示

char字符串中的A是UTF-16值。值≥0x1000(例如,大多数表情符号)的Unicode代码点使用两个char位置。要计算字符串中的Unicode代码点数,无论每个代码点是否适合UTF-16char值,都可以使用以下codePointCount方法:

int length = str.codePointCount(0, str.length());

从Java 8开始,您还可以使用代码点流:

int length = str.codePoints().count();