c++ - 如何检测终端中的unicode字符串宽度?

标签 c++ linux unicode utf-8 utf-32

我正在开发一个基于终端的程序,该程序支持 unicode。在某些情况下,我需要在打印之前确定一个字符串将使用多少个终端列。不幸的是有些字符是 2 列宽(中文等),但我找到了 this answer这表明检测全角字符的好方法是从 ICU 库调用 u_getIntPropertyValue()。

现在我正在尝试解析我的 UTF8 字符串的字符并将它们传递给此函数。我现在遇到的问题是 u_getIntPropertyValue() 需要一个 UTF-32 代码点。

从 utf8 字符串获取它的最佳方法是什么?我目前正在尝试使用 boost::locale(在我的程序的其他地方使用)来执行此操作,但我无法获得干净的转换。来自 boost::locale 的我的 UTF32 字符串预先附加了 zero-width character指示字节顺序。显然我可以跳过字符串的前四个字节,但是有没有更简洁的方法来做到这一点?

这是我目前丑陋的解决方案:

inline size_t utf8PrintableSize(const std::string &str, std::locale loc)
{
    namespace ba = boost::locale::boundary;
    ba::ssegment_index map(ba::character, str.begin(), str.end(), loc);
    size_t widthCount = 0;
    for (ba::ssegment_index::iterator it = map.begin(); it != map.end(); ++it)
    {
        ++widthCount;
        std::string utf32Char = boost::locale::conv::from_utf(it->str(), std::string("utf-32"));

        UChar32 utf32Codepoint = 0;
        memcpy(&utf32Codepoint, utf32Char.c_str()+4, sizeof(UChar32));

        int width = u_getIntPropertyValue(utf32Codepoint, UCHAR_EAST_ASIAN_WIDTH);
        if ((width == U_EA_FULLWIDTH) || (width == U_EA_WIDE))
        {
            ++widthCount;
        }

    }
    return widthCount;
}

最佳答案

@n.m 是正确的:有一种简单的方法可以直接使用 ICS 执行此操作。更新后的代码如下。我怀疑在这种情况下我可能只使用 UnicodeString 并绕过整个提升语言环境的使用。

inline size_t utf8PrintableSize(const std::string &str, std::locale loc)
{
    namespace ba = boost::locale::boundary;
    ba::ssegment_index map(ba::character, str.begin(), str.end(), loc);
    size_t widthCount = 0;
    for (ba::ssegment_index::iterator it = map.begin(); it != map.end(); ++it)
    {
        ++widthCount;

        //Note: Some unicode characters are 'full width' and consume more than one
        // column on output.  We will increment widthCount one extra time for
        // these characters to ensure that space is properly allocated
        UnicodeString ucs = UnicodeString::fromUTF8(StringPiece(it->str()));
        UChar32 codePoint = ucs.char32At(0);

        int width = u_getIntPropertyValue(codePoint, UCHAR_EAST_ASIAN_WIDTH);
        if ((width == U_EA_FULLWIDTH) || (width == U_EA_WIDE))
        {
            ++widthCount;
        }

    }
    return widthCount;
}

关于c++ - 如何检测终端中的unicode字符串宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397118/

相关文章:

c++ - 用随机值填充我的数组 C++

c++ - 包装器是从 strcat_s() 到 strcat() 吗?如果没有,是否可以创建一个?

linux - 在与符号链接(symbolic link)同名的目录中提取符号链接(symbolic link) zip 文件的内容

linux - 如何在 Linux 上安全且事务性地替换文件?

java - 将字符保存到文件时出现问题

c++ - 返回对类成员容器的元素的引用

c++ - 如何在 C++ 中获取列表?

linux - 如何为 RHEL 6 找到 libstdc++.so.6 : that contain GLIBCXX_3. 4.19?

Java Selenium/HtmlunitDriver 打开错误的网站

c++ - 什么是用于 C++ UTF-8/UTF-16 文本编码的小型 LGPL 库?