如何将 UTF-8 std::string 转换为 UTF-16 std::wstring?
如果我有 UTF-8 std::string
如何将其转换为 UTF-16 std::wstring
?实际上,我想比较两个波斯语单词。
If I have a UTF-8 std::string
how do I convert it to a UTF-16 std::wstring
? Actually, I want to compare two Persian words.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是使用 C++11 执行此操作的方法:
这些是您需要的标头:
此处提供了更完整的示例:
http://en.cppreference.com/w/cpp/locale/wstring_convert/from_bytes
This is how you do it with C++11:
And these are the headers you need:
A more complete example available here:
http://en.cppreference.com/w/cpp/locale/wstring_convert/from_bytes
这是一些代码。仅进行了少量测试,可能还有一些改进。调用此函数将 UTF-8 字符串转换为 UTF-16 wstring。如果它认为输入字符串不是 UTF-8 那么它将抛出异常,否则它返回等效的 UTF-16 wstring。
Here's some code. Only lightly tested and there's probably a few improvements. Call this function to convert a UTF-8 string to a UTF-16 wstring. If it thinks the input string is not UTF-8 then it will throw an exception, otherwise it returns the equivalent UTF-16 wstring.
有一些相关的问答此处和这里值得一试 读。
基本上,您需要将字符串转换为通用格式——我的偏好始终是转换为 UTF-8,但您的里程可能会谨慎。
有很多为进行转换而编写的软件——转换是直接进行的,可以在几个小时内完成——但是为什么不选择已经完成的内容,例如 UTF-8 CPP
There are some relevant Q&A here and here which is worth a read.
Basically you need to convert the string to a common format -- my preference is always to convert to UTF-8, but your mileage may wary.
There have been lots of software written for doing the conversion -- the conversion is straigth forwards and can be written in a few hours -- however why not pick up something already done such as the UTF-8 CPP
要在两种类型之间进行转换,您应该使用: std::codecvt_utf8_utf16< wchar_t>
请注意我用来定义 UTF16 (L) 和 UTF8 (u8) 的字符串前缀。
To convert between the 2 types, you should use: std::codecvt_utf8_utf16< wchar_t>
Note the string prefixes I use to define UTF16 (L) and UTF8 (u8).
Microsoft 为此类转换开发了一个漂亮的库,作为其 Casablanca 项目的一部分,也称为 CPPRESTSDK。这在命名空间 utility::conversions 下标记。
它的简单用法在使用名称空间时看起来像这样
Microsoft has developed a beautiful library for such conversions as part of their Casablanca project also named as CPPRESTSDK. This is marked under the namespaces utility::conversions.
A simple usage of it would look something like this on using namespace
使用 winrt,您可以通过
winrt::to_hstring()
轻松将 utf8 的 std::string 转换为 hstring(wchar)with winrt, you can easily convert std::string of utf8 to hstring(wchar) by
winrt::to_hstring()
此页面似乎也很有用: http://www.codeproject.com/KB/string/UtfConverter .aspx
在该页面的评论部分,还有一些针对此任务的有趣建议,例如:
或者
虽然我不确定这些方法的有效性...
This page also seems useful: http://www.codeproject.com/KB/string/UtfConverter.aspx
In the comment section of that page, there are also some interesting suggestions for this task like:
Or
Though I'm not sure the validity of these approaches...