C ++字符串代码点和代码单元的任何好的解决方案?

时间:2017-04-09 02:03:21

标签: c++ unicode utf-8 utf-16

在Java中,String包含方法:

length()/charAt(), codePointCount()/codePointAt()

C ++ 11有std::string a = u8"很烫烫的一锅汤";

但是a.size()是char数组的长度,不能索引unicode char。

C ++字符串中是否有unicode解决方案?

1 个答案:

答案 0 :(得分:3)

在进行字符操作之前,我通常会将UTF-8字符串转换为宽UTF-32/UCS-2字符串。 C++确实给了我们这样做的功能,但它们不是非常用户友好,所以我在这里编写了一些更好的转换函数:

// This should convert to whatever the system wide character encoding 
// is for the platform (UTF-32/Linux - UCS-2/Windows)
std::string ws_to_utf8(std::wstring const& s)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cnv;
    std::string utf8 = cnv.to_bytes(s);
    if(cnv.converted() < s.size())
        throw std::runtime_error("incomplete conversion");
    return utf8;
}

std::wstring utf8_to_ws(std::string const& utf8)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cnv;
    std::wstring s = cnv.from_bytes(utf8);
    if(cnv.converted() < utf8.size())
        throw std::runtime_error("incomplete conversion");
    return s;
}

int main()
{
    std::string s = u8"很烫烫的一锅汤";

    auto w = utf8_to_ws(s); // convert to wide (UTF-32/UCS-2)

    // now we can use code-point indexes on the wide string

    std::cout << s << " is " << w.size() << " characters long" << '\n';
}

<强>输出:

很烫烫的一锅汤 is 7 characters long

如果您想要转换为UTF-32而不管平台,那么您可以使用以下(未经过良好测试的)转换例程:

std::string utf32_to_utf8(std::u32string const& utf32)
{
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> cnv;
    std::string utf8 = cnv.to_bytes(utf32);
    if(cnv.converted() < utf32.size())
        throw std::runtime_error("incomplete conversion");
    return utf8;
}

std::u32string utf8_to_utf32(std::string const& utf8)
{
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> cnv;
    std::u32string utf32 = cnv.from_bytes(utf8);
    if(cnv.converted() < utf8.size())
        throw std::runtime_error("incomplete conversion");
    return utf32;
}

注意:截至C++17 std::wstring_convert 已弃用

然而我仍然喜欢在第三方库上使用它,因为它是可移植,它避免了外部依赖性,在提供替换之前不会删除它并且在所有情况下都可以轻松替换这些函数的实现,而无需更改使用它们的所有代码。