Truncate Text At Code Point Boundary
Cut long text to a code point budget before appending an ellipsis, so surrogate pairs and CJK characters never split mid-character.
Code
public class TruncateEllipsis {
// cut on a code point boundary, never inside a surrogate pair
static String truncate(String text, int codePointLimit) {
if (text.codePointCount(0, text.length()) <= codePointLimit) {
return text;
}
int cutOffset = text.offsetByCodePoints(0, codePointLimit - 1);
return text.substring(0, cutOffset) + "…";
}
public static void main(String[] args) {
String[] samples = {
"abcdefghij",
"café déjà vu",
"🚀🚀🚀🚀🚀",
"short"};
for (String sample : samples) {
String cut = truncate(sample, 6);
System.out.println(sample + " (" + sample.codePointCount(0, sample.length())
+ " code points) -> " + cut
+ " (" + cut.codePointCount(0, cut.length()) + " code points)");
}
}
}What the code does
Truncate Text At Code Point Boundary keeps everything in the class TruncateEllipsis and the functions truncate and main.
for (String sample : samples) is the loop that carries the per-item work.
Caveats
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Applying it
Entry signature: static String truncate(String text, int codePointLimit)
Execute the file and main walks through truncate, in that order.
Statements that set the outcome here
return text.substring(0, cutOffset) + "…";
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.Unicode Code Point ExplorerExplore Unicode code points of any text input. View each character with its code point, UTF-8 byte sequence, and official name for internationalization debugging.
FAQ
- How do you run Truncate Text At Code Point Boundary?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.