【发布时间】:2016-09-20 16:41:50
【问题描述】:
我正在开发一个支持 unicode 的基于终端的程序。在某些情况下,我需要在打印之前确定一个字符串将消耗多少个终端列。不幸的是,有些字符是 2 列宽(中文等),但我发现 this answer 表明检测全角字符的好方法是从 ICU 库中调用 u_getIntPropertyValue()。
现在我正在尝试解析我的 UTF8 字符串的字符并将它们传递给这个函数。我现在遇到的问题是 u_getIntPropertyValue() 需要一个 UTF-32 代码点。
从 utf8 字符串中获取此信息的最佳方法是什么?我目前正在尝试使用 boost::locale (在我的程序中的其他地方使用)来做到这一点,但我无法获得干净的转换。我来自 boost::locale 的 UTF32 字符串前面带有 zero-width character 以指示字节顺序。显然我可以跳过字符串的前四个字节,但是有没有更简洁的方法呢?
这是我目前的丑陋解决方案:
inline size_t utf8PrintableSize(const std::string &str, std::locale loc)
{
namespace ba = boost::locale::boundary;
ba::ssegment_index map(ba::character, str.begin(), str.end(), loc);
size_t widthCount = 0;
for (ba::ssegment_index::iterator it = map.begin(); it != map.end(); ++it)
{
++widthCount;
std::string utf32Char = boost::locale::conv::from_utf(it->str(), std::string("utf-32"));
UChar32 utf32Codepoint = 0;
memcpy(&utf32Codepoint, utf32Char.c_str()+4, sizeof(UChar32));
int width = u_getIntPropertyValue(utf32Codepoint, UCHAR_EAST_ASIAN_WIDTH);
if ((width == U_EA_FULLWIDTH) || (width == U_EA_WIDE))
{
++widthCount;
}
}
return widthCount;
}
【问题讨论】:
-
如果你已经在使用ICU,为什么不把它也用于utf8-to-utf32的转换呢?
-
我对重症监护室不熟悉。我试图使用 boost::locale 来使我免受大部分复杂性的影响。有没有一种简单的方法可以直接从 ICU 获取这个 utf32 代码点?
-
我也不熟悉它,但我知道它拥有任何人想要从 unicode 库中获得的一切。花点时间用谷歌,你会找到的。
标签: c++ linux unicode utf-8 utf-32