简体   繁体   English

utf8和utf16转换

[英]utf8 and utf16 conversion

I have a wchar_t string, for example, L"hao123--我的上网主页", I can convert it to utf8 我有一个wchar_t字符串,例如L“ hao123--我的上网主页”,我可以将其转换为utf8

encoding, the output string is "hao123锛嶏紞鎴戠殑涓婄綉涓婚〉", but finally, I must write this 编码,输出字符串是“ hao123锛嶏紞鎴戠殑涓婄绣涓婚〉”,但是最后,我必须写这个

string to a plain text file, its format is utf16 (I know this from others), "hao123\-\-\我\的\上\网\主\页". 字符串转换为纯文本文件,其格式为utf16(我从其他人知道),“ hao123 \\ uFF0D \\ uFF0D \\ u6211 \\ u7684 \\ u4E0A \\ u7F51 \\ u4E3B \\ u9875”。

Because I must save it in C++ std string and then write it to a file, How can I convert 因为我必须将其保存在C ++ std字符串中,然后将其写入文件,所以我该如何转换

"hao123锛嶏紞鎴戠殑涓婄綉涓婚〉" to "hao123\-\-\我\的\上\网\主\页" in char or C++ std string ? char或C ++ std字符串中的“ hao123锛嶏紞鎴戠殑涓婄绣涓婚〉”到“ hao123 \\ uFF0D \\ uFF0D \\ u6211 \\ u7684 \\ u4E0A \\ u7F51 \\ u4E3B \\ u9875”?

Can anyone give me some tips? 谁能给我一些提示?

Thanks in advance! 提前致谢!

In C++11 this can be done with: 在C ++ 11中,可以使用:

#include <locale>
#include <codecvt>
#include <string>
#include <iostream>

int main()
{
    std::wstring_convert<std::codecvt_utf16<wchar_t> > myconv;
    std::wstring ws(L"hao123--\x6211\x7684\x4E0A\x7F51\x4E3B\x9875");
    std::string bs = myconv.to_bytes(ws);
    std::cout << bs << '\n';
}

我自己编写了转换函数,有关更多信息,请访问C ++ Unicode UTF-16编码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM