std :: u32string转换为/从std :: string和std :: u16string

Fir*_*cer 5 c++ linux windows unicode c++11

我需要为不同的API /模块在UTF-8,UTF-16和UTF-32之间进行转换,因为我知道可以选择使用C++ 11查看新的字符串类型.

它看起来像我可以使用string,u16stringu32string为UTF-8,UTF-16和UTF-32.我还发现codecvt_utf8codecvt_utf16这一下就能够做到之间的转换char或者char16_tchar32_t什么看起来像一个较高的水平wstring_convert,但只出现与字节/工作std::string和文件不是很大.

我是不是想以wstring_convert某种方式使用UTF-16↔UTF-32和UTF-8↔UTF-32机箱?我只是真的找到了UTF-8到UTF-16的例子,我甚至不确定它在Linux上wchar_t通常被认为是UTF-32 是正确的......还是直接用那些代码解析器做一些更复杂的事情?

或者这仍然没有真正处于可用状态,我应该坚持使用8,16和32位无符号整数的现有小程序?

Rem*_*eau 19

如果你阅读CppReference.com的文档wstring_convert,codecvt_utf8,codecvt_utf16,和codecvt_utf8_utf16,页面包括表,告诉你到底可以使用什么不同的UTF转换.

表

是的,你会std::wstring_convert用来促进各种UTF之间的转换.尽管它的名字,它不限于只是std::wstring,它实际上与任何操作std::basic_string类型(其中std::string,std::wstringstd::uXXstring都是基于).

类模板std :: wstring_convert 使用单独的代码转换方面Codecvt 执行字节字符串std::string和宽字符串之间的std::basic_string<Elem>转换.std :: wstring_convert假定转换构面的所有权,并且不能使用由区域设置管理的构面.适用于std :: wstring_convert的标准方面是用于UTF-8/UCS2和UTF-8/UCS4转换的std :: codecvt_utf8和用于UTF-8/UTF-16转换的std :: codecvt_utf8_utf16.

例如:

typedef std::string u8string;

u8string To_UTF8(const std::u16string &s)
{
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.to_bytes(s);
}

u8string To_UTF8(const std::u32string &s)
{
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
    return conv.to_bytes(s);
}

std::u16string To_UTF16(const u8string &s)
{
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conv;
    return conv.from_bytes(s);
}

std::u16string To_UTF16(const std::u32string &s)
{
    std::wstring_convert<std::codecvt_utf16<char32_t>, char32_t> conv;
    std::string bytes = conv.to_bytes(s);
    return std::u16string(reinterpret_cast<const char16_t*>(bytes.c_str()), bytes.length()/sizeof(char16_t));
}

std::u32string To_UTF32(const u8string &s)
{
    std::wstring_convert<codecvt_utf8<char32_t>, char32_t> conv;
    return conv.from_bytes(s);
}

std::u32string To_UTF32(const std::u16string &s)
{
    const char16_t *pData = s.c_str();
    std::wstring_convert<std::codecvt_utf16<char32_t>, char32_t> conv;
    return conv.from_bytes(reinterpret_cast<const char*>(pData), reinterpret_cast<const char*>(pData+s.length()));
}
Run Code Online (Sandbox Code Playgroud)