繁体   English   中英

将 ICU Unicode 字符串转换为 std::wstring(或 wchar_t*)

[英]Convert ICU Unicode string to std::wstring (or wchar_t*)

是否有 icu UnicodeString从 icu UnicodeString 创建std::wstring 我一直在搜索 ICU 手册,但一直找不到。

(我知道我可以将UnicodeString转换为UTF8 ,然后转换为依赖于平台的wchar_t*但我正在 UnicodeString 中寻找一个UnicodeString可以进行此转换。

C++ 标准没有规定std::wstring的任何特定编码。 在 Windows 系统上, wchar_t是 16 位的,而在 Linux、macOS 和其他几个平台上, wchar_t是 32 位的。 就 C++ 的std::wstring而言,它只是wchar_t的任意序列,其方式与std::string只是char的任意序列大致相同。

似乎icu::UnicodeString没有创建std::wstring的内置方法,但如果你真的想创建一个std::wstring ,你可以像这样使用基于 C 的 API u_strToWCS()

icu::UnicodeString ustr = /* get from somewhere */;
std::wstring wstr;

int32_t requiredSize;
UErrorCode error = U_ZERO_ERROR;

// obtain the size of string we need
u_strToWCS(nullptr, 0, &requiredSize, ustr.getBuffer(), ustr.length(), &error);

// resize accordingly (this will not include any terminating null character, but it also doesn't need to either)
wstr.resize(requiredSize);

// copy the UnicodeString buffer to the std::wstring.
u_strToWCS(wstr.data(), wstr.size(), nullptr, ustr.getBuffer(), ustr.length(), &error);

据推测, u_strToWCS()将使用最有效的方法从UChar转换为wchar_t (如果它们的大小相同,那么我想它只是一个直接的副本)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM