Converting “normal” std::string to utf-8

后端 未结 1 2063
一向
一向 2021-02-12 22:56

Let\'s see if I can explain this without too many factual errors...

I\'m writing a string class and I want it to use utf-8 (stored in a std::string) as it\'

相关标签:
1条回答
  • 2021-02-12 23:26

    If your "normal string" is encoded using the system's code page and you want to convert it to UTF-8 then this should work:

    std::string codepage_str;
    int size = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, codepage_str.c_str(),
                                   codepage_str.length(), nullptr, 0);
    std::wstring utf16_str(size, '\0');
    MultiByteToWideChar(CP_ACP, MB_COMPOSITE, codepage_str.c_str(),
                        codepage_str.length(), &utf16_str[0], size);
    
    int utf8_size = WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(),
                                        utf16_str.length(), nullptr, 0,
                                        nullptr, nullptr);
    std::string utf8_str(utf8_size, '\0');
    WideCharToMultiByte(CP_UTF8, 0, utf16_str.c_str(),
                        utf16_str.length(), &utf8_str[0], utf8_size,
                        nullptr, nullptr);
    
    0 讨论(0)
提交回复
热议问题