c++ - UTF8 字符数组到 std::wstring

标签 c++ unicode utf-8 x11 xcb

我只是想获取 x11 窗口标题,并将其存储在 std::wstring 中。我使用这样的命令来获取标题

auto req_title = xcb_get_property(conn, 0, window, XCB_ATOM_WM_NAME, XCB_GET_PROPERTY_TYPE_ANY, 0, 100);
auto res_title = xcb_get_property_reply(conn, req_title, nullptr);

之后,我可以获得存储在 char 数组中的标题。如何将此数组转换为 wstring?

最佳答案

当前解决方案

您可以使用 std::wstring_convert使用 codecvtstringwstring 相互转换指定要执行的转换。

使用示例:

string so=u8"Jérôme Ângle"; 
wstring st; 
wstring_convert<std::codecvt_utf8<wchar_t>,wchar_t> converter;
st = converter.from_bytes(so);

如果你有一个 c 字符串(char 数组),from_bytes() 的重载将完全按照你的意愿执行:

char p[]=u8"Jérôme Ângle";
wstring ws = converter.from_bytes(p);

Online demo

是否可持续?

正如评论中指出的那样,C++17 has deprecated codecvtwstring_convert 实用程序:

These features are hard to use correctly, and there are doubts whether they are even specified correctly. Users should use dedicated text-processing libraries instead.

此外,wstring 是基于 wchar_t 的,后者在 linux 系统和 windows 系统上具有非常不同的编码。

所以第一个问题是问为什么需要 wstring,为什么不保留 utf-8 everywhere .

根据原因,您可以考虑使用:

  • ICU及其 UnicodeString获得完整、深入的 unicode 支持
  • boost.locale它的 to_utfutf_to_utf ,用于常见的 unicode 相关任务。
  • utf8-cpp用于以 unicode 方式处理 utf8 字符串(注意,似乎没有维护)。

关于c++ - UTF8 字符数组到 std::wstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53177771/

相关文章:

c++ - 为什么不推荐使用 isascii()?

python - 用 '\x' 替换 = 然后在 python 中解码

windows - Unicode解码错误: 'utf8' codec can't decode byte 0x92 in position 377826: invalid start byte

c++ - CUDA 多线程 : __threadfence not preventing multiple threads from accessing resource

c++ - 可变参数宏,用于从未知参数集合生成字符串 vector

python - 在基于 Debian 的系统上,如何找到一种字体具有字形的 Unicode 代码点?

scala - 使用Scala和IntelliJ,显示unicode箭头,但不更改源代码

tomcat - 奇怪的问题,Tomcat Webapp UTF-8 Character每次重启或每次重新部署后都无法正确显示

c++ - 在 Linux 上从 UART 进行阻塞 read()

objective-c - 搜索时如何忽略Unicode字符?