gpt4 book ai didi

c++ - 如何检测终端中的unicode字符串宽度?

转载 作者:IT王子 更新时间:2023-10-29 00:34:54 26 4
gpt4 key购买 nike

我正在开发一个基于终端的程序,该程序支持 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;
}

最佳答案

@n.m 是正确的:有一种简单的方法可以直接使用 ICS 执行此操作。更新后的代码如下。我怀疑在这种情况下我可能只使用 UnicodeString 并绕过整个提升语言环境的使用。

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;

//Note: Some unicode characters are 'full width' and consume more than one
// column on output. We will increment widthCount one extra time for
// these characters to ensure that space is properly allocated
UnicodeString ucs = UnicodeString::fromUTF8(StringPiece(it->str()));
UChar32 codePoint = ucs.char32At(0);

int width = u_getIntPropertyValue(codePoint, UCHAR_EAST_ASIAN_WIDTH);
if ((width == U_EA_FULLWIDTH) || (width == U_EA_WIDE))
{
++widthCount;
}

}
return widthCount;
}

关于c++ - 如何检测终端中的unicode字符串宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com