我正在尝试完成一个非常简单的任务:将支持 Unicode 的 wstring
转换为以 UTF8 字节编码的 string
,然后再反过来:将包含 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 facetеҮәдәҶд»Җд№Ҳй—®йўҳпјҹ - Ben Voigtwchar_t
/wstring
在存储代码点方面是一个不好的选择,因为不能保证wchar_t
足够宽以涵盖所有的码点(如果我没记错,在Windows上,对于BMP之外的码点来说,wchar_t
是不够宽的)。 - etarion