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.

JavaForm Validation

Code

snippet
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

FAQ

How do you run Truncate Text At Code Point Boundary?
Nothing to install first — run the file and the program does the rest.