問題:
給定一個字串或字元變量,我們如何將其內容分配給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中文網其他相關文章!