如何将Unicode编号转换为std::wstring?
将Unicode编号转换为std::wstring的简便方法
先纠正一个小错误
你给出的U+1E9E对应的十进制值有误,正确的十进制是7838(十六进制0x1E9E),16785054对应的是0x19000E,并非ẞ的码点。
方法1:直接构造(适用于BMP码点)
如果Unicode码点属于基本多语言平面(BMP,U+0000至U+FFFF),可以直接将码点值转换为wchar_t,再初始化std::wstring。U+1E9E属于BMP,代码非常简洁:
// 用十六进制码点初始化 std::wstring s(1, static_cast<wchar_t>(0x1E9E)); // 或者用十进制码点 std::wstring s(1, static_cast<wchar_t>(7838));
执行后s就包含字符ẞ。
方法2:通用兼容法(支持所有Unicode码点)
如果需要处理超出BMP的码点(U+10000及以上),可以借助C++标准库的编码转换工具,先构造std::u32string(每个元素对应一个完整Unicode码点),再转换为std::wstring:
#include <string> #include <locale> #include <codecvt> std::wstring codepoint_to_wstring(char32_t codepoint) { std::u32string u32_str(1, codepoint); // 转换为UTF-8再转回宽字符,兼容Windows(UTF-16)和Linux(UTF-32)环境 std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; std::string utf8_str = converter.to_bytes( reinterpret_cast<const wchar_t*>(u32_str.data()), reinterpret_cast<const wchar_t*>(u32_str.data() + u32_str.size()) ); return converter.from_bytes(utf8_str); } // 使用示例 std::wstring s = codepoint_to_wstring(0x1E9E); // 得到ẞ
注意:C++17中std::wstring_convert被标记为弃用,但主流编译器(如GCC、MSVC)仍提供支持;如果需要更现代的实现,可考虑使用ICU等第三方库。
方法3:Windows平台专属实现
在Windows上,也可以通过系统APIMultiByteToWideChar完成转换,先将码点转为UTF-8,再转成宽字符:
#include <windows.h> #include <string> std::wstring codepoint_to_wstring_win(char32_t codepoint) { char utf8_buf[4] = {0}; int utf8_len = 0; // 将Unicode码点编码为UTF-8 if (codepoint <= 0x7F) { utf8_buf[0] = static_cast<char>(codepoint); utf8_len = 1; } else if (codepoint <= 0x7FF) { utf8_buf[0] = static_cast<char>(0xC0 | ((codepoint >> 6) & 0x1F)); utf8_buf[1] = static_cast<char>(0x80 | (codepoint & 0x3F)); utf8_len = 2; } else if (codepoint <= 0xFFFF) { utf8_buf[0] = static_cast<char>(0xE0 | ((codepoint >> 12) & 0x0F)); utf8_buf[1] = static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)); utf8_buf[2] = static_cast<char>(0x80 | (codepoint & 0x3F)); utf8_len = 3; } else if (codepoint <= 0x10FFFF) { utf8_buf[0] = static_cast<char>(0xF0 | ((codepoint >> 18) & 0x07)); utf8_buf[1] = static_cast<char>(0x80 | ((codepoint >> 12) & 0x3F)); utf8_buf[2] = static_cast<char>(0x80 | ((codepoint >> 6) & 0x3F)); utf8_buf[3] = static_cast<char>(0x80 | (codepoint & 0x3F)); utf8_len = 4; } else { return L""; // 无效码点,返回空字符串 } // 转换UTF-8为宽字符 int wide_len = MultiByteToWideChar(CP_UTF8, 0, utf8_buf, utf8_len, nullptr, 0); std::wstring wide_str(wide_len, 0); MultiByteToWideChar(CP_UTF8, 0, utf8_buf, utf8_len, &wide_str[0], wide_len); return wide_str; } // 使用示例 std::wstring s = codepoint_to_wstring_win(0x1E9E);
内容的提问来源于stack exchange,提问作者user3443063
相关产品推荐
相关产品推荐

