Code Points Versus String Length

Validate text length by code points instead of chars: codePointCount counts one emoji as one, and codePoints().limit clips without corrupting surrogates.

JavaForm Validation

Code

snippet
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);
    }
}

How the snippet works

Code Points Versus String Length keeps everything in the class UsernameValidator and the function main.

Applying it

Running the file prints labeled results such as chars:, code points:, clipped: — each operation’s effect is visible in the output.

Statements that matter

.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();

Interactive Tools for This Topic

FAQ

What does Code Points Versus String Length print when run?
Execute the whole file; each printed line is prefixed with a label like `chars:`, `code points:`, `clipped:`.