Display Width For East Asian Text

Count terminal columns where CJK and fullwidth characters occupy two cells, so padded tables align where String length() undercounts wide text.

JavaCli Tooling

Code

snippet
public class DisplayWidth {

    // East Asian wide characters count two terminal cells, everything else one
    static int charWidth(int codePoint) {
        if (Character.isISOControl(codePoint)) return 0;
        return (codePoint >= 0x1100 && codePoint <= 0x115F)      // Hangul Jamo
                || (codePoint >= 0x2E80 && codePoint <= 0xA4CF)  // CJK radicals through Yi: covers kana and han
                || (codePoint >= 0xAC00 && codePoint <= 0xD7A3)  // Hangul syllables
                || (codePoint >= 0xF900 && codePoint <= 0xFAFF)  // CJK compatibility ideographs
                || (codePoint >= 0xFF00 && codePoint <= 0xFF60)  // fullwidth forms
                || (codePoint >= 0xFFE0 && codePoint <= 0xFFE6)
                ? 2 : 1;
    }

    static int displayWidth(String text) {
        return text.codePoints().map(DisplayWidth::charWidth).sum();
    }

    // pad to display width on the right: String length() counts wide characters narrow, so mixed tables drift out of alignment
    static String padEnd(String text, int width) {
        return text + " ".repeat(Math.max(0, width - displayWidth(text)));
    }

    public static void main(String[] args) {
        String[][] rows = {
                {"1", "Ada", "us-east-1"},
                {"2", "华为", "cn-north-1"},
                {"3", "パトラ", "ap-northeast-1"},
        };
        for (String[] row : rows) {
            System.out.println(padEnd(row[0], 4) + padEnd(row[1], 12) + row[2]);
        }
        System.out.println("width of 华为 = " + displayWidth("华为"));
        System.out.println("length of 华为 = " + "华为".length());
    }
}

Inside the snippet

Structurally, expect the class DisplayWidth and the functions charWidth, displayWidth, padEnd and main and nothing else.

The loop for (String[] row : rows) is the only repeated construct.

Using it

The primary signature is static int charWidth(int codePoint)

The demo output is labeled (width of 华为 =, length of 华为 =); each label names the call that printed it.

The entry point wires padEnd and displayWidth together — run it once and the whole demo flows.

Key statements

return text.codePoints().map(DisplayWidth::charWidth).sum();
return text + " ".repeat(Math.max(0, width - displayWidth(text)));
if (Character.isISOControl(codePoint)) return 0;

Interactive Tools for This Topic

FAQ

What does Display Width For East Asian Text print when run?
Execute the whole file; each printed line is prefixed with a label like `width of 华为 =`, `length of 华为 =`.