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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.