【问题标题】:Compute the width of a string in monspaced font以等宽字体计算字符串的宽度
【发布时间】:2019-04-08 05:03:58
【问题描述】:

为了在终端中正确格式化某些文本(我假设使用等宽字体),我需要计算字符串的“长度”。棘手的部分是我需要它在显示器上使用的长度(固定宽度字符的数量)。

我最初使用length 函数,但它返回代码点的数量。我还尝试使用以下方法计算 graphemes 的数量:

sub width {
    my $str = shift;
    my $count = 0;
    while ($str =~ /\X/g) {
        $count++;
    }
    return $count;
}

(归功于Tom Christiansen)。

但这仍然不是我需要的,因为一些字素是我的字体(SF Mono Regular)的双倍宽度,例如表情符号和亚洲字符。

【问题讨论】:

    标签: perl unicode text-formatting


    【解决方案1】:

    经过进一步研究,我发现了Text::CharWidth CPAN 模块,它提供了mbswidth 功能,正是我需要的。

    use Text::CharWidth qw(mbswidth);
    
    mbswidth ("??"); # returns 4
    mbswidth ("あら"); # returns 4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多