我知道要在C++中获得unicode字符,我可以这样做:
std::wstring str = L"\u4FF0";
但是,如果我想获取4FF0到5FF0范围内的所有字符怎么办?是否可以动态构建unicode字符?我想到的是这样的伪代码:
for (int i = 20464; i < 24560; i++ { // From 4FF0 to 5FF0
std::wstring str = L"\u" + hexa(i); // build the unicode character
// do something with str
}
我将如何在C++中做到这一点?
最佳答案
wstring中包含的wchar_t类型是整数类型,因此您可以直接使用它:
for (wchar_t c = 0x4ff0; c <= 0x5ff0; ++c) {
std::wstring str(1, c);
// do something with str
}
请谨慎尝试使用大于0xffff的字符来执行此操作,因为取决于平台(例如Windows),它们将不适合wchar_t。
例如,如果您想查看字符串中的Emoticon block,则可以创建代理对:
std::wstring str;
for (int c = 0x1f600; c <= 0x1f64f; ++c) {
if (c <= 0xffff || sizeof(wchar_t) > 2)
str.append(1, (wchar_t)c);
else {
str.append(1, (wchar_t)(0xd800 | ((c - 0x10000) >> 10)));
str.append(1, (wchar_t)(0xdc00 | ((c - 0x10000) & 0x3ff)));
}
}