问题:
给定一个字符串或字符变量,我们如何将其内容分配给wstring 或 wchar_t 变量?
解决方案:
假设输入字符串以 UTF-8 编码,标准库(C 11 及更高版本)包括UTF-8 和 UTF-8 之间转换的几种技术UTF-16:
#include <locale> #include <codecvt> #include <string> using namespace std; // Create a converter using the UTF-8/UTF-16 codecvt wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; // Convert a narrow (UTF-8) string to a wide (UTF-16) string wstring wide = converter.from_bytes(narrow); // Convert a wide (UTF-16) string to a narrow (UTF-8) string string narrow = converter.to_bytes(wide);
示例(可在线编译和运行):
#include <iostream> #include <locale> #include <codecvt> #include <string> int main() { // Sample input string in UTF-8 (see notes below for real-world scenarios): string s = "おはよう"; // Create a wstring to store the converted string wstring ws; // Convert the narrow (UTF-8) string to wide (UTF-16) std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; ws = conv.from_bytes(s); // Print the converted wstring wcout << ws << endl; return 0; }
注释:
以上是如何在 C 中将字符串(或字符)转换为 wstring(或 wchar_t)?的详细内容。更多信息请关注PHP中文网其他相关文章!