← 中文资源

简体中文版本

东亚文本的显示列宽

终端排版要按显示列数而不是字符数:CJK 与全角字符占两列,String length() 会算窄;按码点累计宽度再补空格,中英混排表格才能对齐。

阅读英文原文

实现说明

东亚文本的显示列宽的核心是类 DisplayWidth和函数 charWidth、displayWidth、padEnd、main。 文件的主干是一个循环——for (String[] row : rows)。

使用要点

  • 直接运行文件,输出会带上标签,比如 width of 华为 =、length of 华为 =——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 padEnd、displayWidth。

常见问题

运行「东亚文本的显示列宽」会打印什么?

整个文件跑完,输出行以 width of 华为 =、length of 华为 = 这类前缀开头。

主签名形如 static int charWidth(int codePoint)

核心语句

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

代码示例

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