5

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

 1 year ago
source link: https://studygolang.com/articles/36114
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

xnotepad · 5天之前 · 850 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    

一段文字中夹杂了中英文字符,需要计算其在屏幕所占的宽度,直接计算字符数量肯定是不行的,因为汉字的宽度是普通英文字符的 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 包含了用于判断字符宽度的功能,对此功能稍加包装即可:

 1import "golang.org/x/text/width"
 2
 3func Width(s string) (w int) {
 4    for _, r := range s {
 5        switch width.LookupRune(r).Kind() {
 6        case width.EastAsianFullwidth, width.EastAsianWide:
 7            w += 2
 8        case width.EastAsianHalfwidth, width.EastAsianNarrow,
 9            width.Neutral, width.EastAsianAmbiguous:
10            w += 1
11        }
12    }
13
14    return w
15}

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

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


有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK