【问题标题】:UTF8 char array to std::wstringUTF8 字符数组到 std::wstring
【发布时间】:2018-11-06 18:22:09
【问题描述】:

我只是想获取 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?

【问题讨论】:

标签: c++ unicode utf-8 x11 xcb


【解决方案1】:

当前解决方案

您可以使用std::wstring_convertstring 转换为wstring 或从wstring 转换,使用codecvt 指定要执行的转换。

使用示例:

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

可持续发展吗?

正如 cmets 中指出的,C++17 has deprecated codecvtwstring_convert 实用程序:

这些功能很难正确使用,而且 怀疑它们是否被正确指定。用户应使用 而是专门的文本处理库。

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

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

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

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

【讨论】:

  • 注意 wstring_convert 和 wbuffer_convert 和 codecvt_utf8 在 C++17 中都被弃用了。
  • from_bytes() 具有接受以 null 结尾的 char* 字符串和两个表示范围的 char* 迭代器的重载,因此您无需将 char 数据包装在临时文件中std::string 如果它不是从一开始就这样开始的。
  • @Christophe IMO 只需将std::wstring_convert 代码包装在简洁的小函数中(例如utf8_to_ws(...)ws_to_utf8(...))然后您就不会在整个应用程序中传播它的使用。然后当它被改变时,你只需要改变一个函数,而不是你的所有代码。
  • @RemyLebeau 感谢您指出这一点!我已经进行了相应的编辑。
  • @Galik 明智的想法!特别是当我在working paper of the standard committee 中阅读“用户应该使用专用的文本处理库。”时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
相关资源
最近更新 更多