C :將字串轉換為wstring,同時保留編碼
給定一個包含日文字元的字串s,並希望分配其內容到一個wstring,ws。任務是在不引入任何編碼問題的情況下執行此任務。
解決方案:
利用 C 11 及更高版本,可以僅使用標準庫完成此任務。
第1 步:包含必要的內容標頭
#include <locale> #include <codecvt> #include <string>
第2 步:建立轉換器
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
此轉換器將處理UTF-8(s的編碼)之間的轉換和UTF-16(ws的編碼)。
std::wstring ws = converter.from_bytes(s);
std::string s = "おはよう"; std::wstring ws; std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; ws = converter.from_bytes(s);
例如:
以上是如何在 C 中安全地將 UTF-8 字串轉換為 wstring?的詳細內容。更多資訊請關注PHP中文網其他相關文章!