【发布时间】:2011-09-02 16:05:45
【问题描述】:
我正在尝试做一个非常简单的任务:获取 unicode-aware wstring 并将其转换为 string,编码为 UTF8 字节,然后相反:获取包含 UTF8 的 string字节并将其转换为支持 unicode 的wstring。
问题是,我需要它跨平台,我需要它与 Boost 一起工作......我似乎无法找到让它工作的方法。我一直在玩弄
- http://www.edobashira.com/2010/03/using-boost-code-facet-for-reading-utf8.html 和
- http://www.boost.org/doc/libs/1_46_0/libs/serialization/doc/codecvt.html
尝试将代码转换为使用 stringstream/wstringstream 而不是任何文件,但似乎没有任何效果。
例如,在 Python 中它看起来像这样:
>>> u"שלום"
u'\u05e9\u05dc\u05d5\u05dd'
>>> u"שלום".encode("utf8")
'\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d'
>>> '\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d'.decode("utf8")
u'\u05e9\u05dc\u05d5\u05dd'
我最终想要的是:
wchar_t uchars[] = {0x5e9, 0x5dc, 0x5d5, 0x5dd, 0};
wstring ws(uchars);
string s = encode_utf8(ws);
// s now holds "\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d"
wstring ws2 = decode_utf8(s);
// ws2 now holds {0x5e9, 0x5dc, 0x5d5, 0x5dd}
我真的不想再增加对 ICU 的依赖或具有这种精神的东西......但据我了解,Boost 应该是可能的。
我们将不胜感激一些示例代码!谢谢
【问题讨论】:
-
imbue不能与stringstream一起使用吗? utf8 codecvt 方面到底出了什么问题? -
wchar_t/wstring是保存代码点的错误选择,因为根本无法保证 wchar_t 足够宽(iirc,在 Windows 上它不适用于BMP。