C ++将字符串(或char *)转换为wstring(或wchar_t *) [英] C++ Convert string (or char*) to wstring (or wchar_t*)
问题描述
string s =おはよう;
wstring ws = FUNCTION(s,ws);
如何将s的内容分配给ws?
搜索google并使用了一些技术,但他们无法分配确切的内容。
假设你的例子中的输入字符串是一个UTF-8编码的不是,通过它的外观,但让我们假设是为了这个解释:-))表示一个你感兴趣的Unicode字符串,那么你的问题可以完全解决与标准库(C ++ 11
> #include< locale>
#include< codecvt>
#include< string>
std :: wstring_convert< std :: codecvt_utf8_utf16< wchar_t>>转换器;
std :: string narrow = converter.to_bytes(wide_utf16_source_string);
std :: wstring wide = converter.from_bytes(narrow_utf8_source_string);
更长的在线可编译和可运行示例:
- http://coliru.stacked-crooked.com/a / b9324a6c8dcf830c (clang)
- 从上一个链接复制并粘贴代码,网址为: http ://webcompiler.cloudapp.net/ (msvc)
注意:
正如评论中所指出的,并在 http://stackoverflow.com/ a / 17106065/6345 有时使用标准库在UTF-8和UTF-16之间转换可能会在不同平台上的结果中产生意想不到的差异。要获得更好的转化,请考虑上所述的 std :: codecvt_utf8
http://en.cppreference.com/w/cpp/locale/codecvt_utf8
string s = "おはよう";
wstring ws = FUNCTION(s, ws);
How would i assign the contents of s to ws?
Searched google and used some techniques but they can't assign the exact content. The content is distorted.
Assuming that the input string in your example (おはよう) is a UTF-8 encoded (which it isn't, by the looks of it, but let's assume it is for the sake of this explanation :-)) representation of a Unicode string of your interest, then your problem can be fully solved with the standard library (C++11 and newer) alone.
The TL;DR version:
#include <locale>
#include <codecvt>
#include <string>
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string narrow = converter.to_bytes(wide_utf16_source_string);
std::wstring wide = converter.from_bytes(narrow_utf8_source_string);
Longer online compilable and runnable example:
- http://coliru.stacked-crooked.com/a/b9324a6c8dcf830c (clang)
- copy-and-paste the code from the previous link at http://webcompiler.cloudapp.net/ (msvc)
Note:
As pointed out in the comments and explained in http://stackoverflow.com/a/17106065/6345 there are cases when using the standard library to convert between UTF-8 and UTF-16 might give unexpected differences in the results on different platforms. For a better conversion, consider std::codecvt_utf8
as described on http://en.cppreference.com/w/cpp/locale/codecvt_utf8
这篇关于C ++将字符串(或char *)转换为wstring(或wchar_t *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!