如何将UTF-8 std :: string转换为UTF-16 std :: wstring?

ali*_*ian 22 c++ string encoding

如果我有UTF-8 std::string怎么把它转换成UTF-16 std::wstring?实际上,我想比较两个波斯语.

Yuc*_*ong 32

这就是你用C++ 11做的方法:

std::string str = "your string in utf8";
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>> converter;
std::wstring wstr = converter.from_bytes(str);
Run Code Online (Sandbox Code Playgroud)

这些是您需要的标题:

#include <iostream>
#include <string>
#include <locale>
#include <codecvt>
Run Code Online (Sandbox Code Playgroud)

这里有一个更完整的例子:http: //en.cppreference.com/w/cpp/locale/wstring_convert/from_bytes

  • 在lubuntu 16.04上不使用g ++ 6.2或clang ++ 3.8 (3认同)
  • 不幸的是,这在 C++17 中已被弃用。https://mariusbancila.ro/blog/2018/07/05/c17-removed-and-deprecated-features/ (3认同)

joh*_*ohn 28

这是一些代码.只有轻微的测试,可能会有一些改进.调用此函数将UTF-8字符串转换为UTF-16 wstring.如果它认为输入字符串不是UTF-8那么它将抛出异常,否则返回等效的UTF-16 wstring.

std::wstring utf8_to_utf16(const std::string& utf8)
{
    std::vector<unsigned long> unicode;
    size_t i = 0;
    while (i < utf8.size())
    {
        unsigned long uni;
        size_t todo;
        bool error = false;
        unsigned char ch = utf8[i++];
        if (ch <= 0x7F)
        {
            uni = ch;
            todo = 0;
        }
        else if (ch <= 0xBF)
        {
            throw std::logic_error("not a UTF-8 string");
        }
        else if (ch <= 0xDF)
        {
            uni = ch&0x1F;
            todo = 1;
        }
        else if (ch <= 0xEF)
        {
            uni = ch&0x0F;
            todo = 2;
        }
        else if (ch <= 0xF7)
        {
            uni = ch&0x07;
            todo = 3;
        }
        else
        {
            throw std::logic_error("not a UTF-8 string");
        }
        for (size_t j = 0; j < todo; ++j)
        {
            if (i == utf8.size())
                throw std::logic_error("not a UTF-8 string");
            unsigned char ch = utf8[i++];
            if (ch < 0x80 || ch > 0xBF)
                throw std::logic_error("not a UTF-8 string");
            uni <<= 6;
            uni += ch & 0x3F;
        }
        if (uni >= 0xD800 && uni <= 0xDFFF)
            throw std::logic_error("not a UTF-8 string");
        if (uni > 0x10FFFF)
            throw std::logic_error("not a UTF-8 string");
        unicode.push_back(uni);
    }
    std::wstring utf16;
    for (size_t i = 0; i < unicode.size(); ++i)
    {
        unsigned long uni = unicode[i];
        if (uni <= 0xFFFF)
        {
            utf16 += (wchar_t)uni;
        }
        else
        {
            uni -= 0x10000;
            utf16 += (wchar_t)((uni >> 10) + 0xD800);
            utf16 += (wchar_t)((uni & 0x3FF) + 0xDC00);
        }
    }
    return utf16;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!谢谢!它工作......我不敢相信:)谢谢你的约翰时间 (2认同)