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

时间:2016-05-23 17:30:27

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

UTF-32是"代码点"的直接表示。个别角色。所以你需要做的就是从UTF-8字符中提取这些字符并将其提供给u_getIntPropertyValue

我拿了你的代码并修改它以使用u8_to_u32_iterator,这似乎就是为了这个:

#include <boost/regex/pending/unicode_iterator.hpp>

inline size_t utf8PrintableSize(const std::string &str, std::locale loc)
{
    size_t widthCount = 0;
    for(boost::u8_to_u32_iterator<std::string::iterator> it(input.begin()), end(input.end()); it!=end; ++it)
    {
        ++widthCount;

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

    }
    return widthCount;
}