Go 中如何获取字符串的宽度

一段文字中夹杂了中英文字符,需要计算其在屏幕所占的宽度,直接计算字符数量肯定是不行的,因为汉字的宽度是普通英文字符的 2 倍, 一种方法先统计汉字的数量,但是还有诸如全角数字等,情况会相对比较复杂。

在 unicode 中为大部分字符都指定了字符所占的宽度:

East Asian Fullwidth (F): 全角字符,比如:123,ABC;
East Asian Halfwidth (H): 半角字符,比如:123, ABC;
East Asian Wide (W): 宽字符,比如汉字;
East Asian Narrow (Na): 窄字符,比如 123,ABC;
East Asian Ambiguous (A): 不确定宽窄的字符,比如 \u01d4;
具体的定义可参考 http://www.unicode.org/reports/tr11/#Definitions。

在 go 的扩展包 width 包含了用于判断字符宽度的功能,对此功能稍加包装即可:

import "golang.org/x/text/width"

func Width(s string) (w int) {
    for _, r := range s {
        switch width.LookupRune(r).Kind() {
        case width.EastAsianFullwidth, width.EastAsianWide:
            w += 2
        case width.EastAsianHalfwidth, width.EastAsianNarrow,
            width.Neutral, width.EastAsianAmbiguous:
            w += 1
        }
    }

    return w
}

本作品采用署名 4.0 国际 (CC BY 4.0)进行许可。

唯一链接:https://caixw.io/posts/2023/go-get-string-width.html

posted @ 2024-07-10 10:19  caixw  阅读(84)  评论(0)    收藏  举报