【发布时间】:2013-09-26 03:35:01
【问题描述】:
如何将 UTF-8 编码的 std::string 转换为 UTF-16 std::string?有可能吗?
不,在我的情况下,我不能使用 std::wstring。
Windows、MSVC-11.0。
【问题讨论】:
标签: c++ string encoding utf-8 utf-16
如何将 UTF-8 编码的 std::string 转换为 UTF-16 std::string?有可能吗?
不,在我的情况下,我不能使用 std::wstring。
Windows、MSVC-11.0。
【问题讨论】:
标签: c++ string encoding utf-8 utf-16
试试这样怎么样:-
std::string s = u8"Your string";
// #include <codecvt>
std::wstring_convert<std::codecvt<char16_t,char,std::mbstate_t>,char16_t> convert;
std::u16string u16 = convert.from_bytes(s);
std::string u8 = convert.to_bytes(u16);
还要检查 this 以了解 UTF 到 UTF 的转换。
来自文档:-
专业化 codecvt 在 UTF-16 和 UTF-8 编码方案,以及专业化 codecvt 在 UTF-32 和 UTF-8 编码方案。
【讨论】:
我在尝试使用 Visual Studio 时遇到了几十个类似的问题,然后就放弃了。在进行转换时存在一个已知问题,例如std::wstring 的转换和使用 std::codecvt。
请看这里: Convert C++ std::string to UTF-16-LE encoded string
我为解决问题所做的工作是从使用 iconv 库的善良海报中复制到代码中的。然后我所要做的就是调用 convert(my_str, strlen(my_str), &used_bytes),其中 my_str 是一个 char[],strlen(my_str) 是它的长度,size_t used_bytes = strlen(my_str)*3;我只是给了它足够的字节来使用它。在该函数中,您可以更改 iconv_t foo = iconv_open("UTF-16", "UTF-8"),调查 setlocale() 并在函数中创建传递给 iconv_open() 的 enc 字符串荣耀尽在上面的链接中。
问题是编译和使用 iconv,它几乎期望在 Windows 上使用 Cygwin 等,但您可以在 Visual Studio 中使用它。 https://github.com/win-iconv/win-iconv 有一个纯 Win32 libiconv,它可能适合您的需求。
我会说试试 iconv,看看它在一个简短的测试程序中是如何进行的。祝你好运!
【讨论】: