实现说明
码点计数与字符串长度可以归结为类 UsernameValidator和函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
chars:、code points:、clipped:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「码点计数与字符串长度」会打印什么?
整个文件跑完,输出行以 chars:、code points:、clipped: 这类前缀开头。
核心语句
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
代码示例
public class UsernameValidator {
public static void main(String[] args) {
// 🙂 是一个码点、两个 char:String.length() 会数出 2
String username = "jane🙂";
System.out.println("chars: " + username.length());
System.out.println("code points: " + username.codePointCount(0, username.length()));
// 按码点截断:先收集码点,再取前 N 个,不会把代理对截成乱码
int limit = 5;
String clipped = username.codePoints()
.limit(limit)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
System.out.println("clipped: " + clipped);
// 是否包含超出 BMP 的增补码点
boolean hasAstral = username.codePoints().anyMatch(cp -> cp > 0xFFFF);
System.out.println("astral: " + hasAstral);
}
}