c++ - 使用 boost 和标准 C++ 进行 Unicode 安全查找

标签 c++ boost unicode

考虑以下代码片段:

namespace bl = boost::locale;
static bl::generator gen;
static auto loc = gen("en_US.UTF-8");
std::string foo8 = u8"Föo";
std::string deco = bl::normalize(foo8,bl::norm_nfd,loc);
std::string comp = bl::normalize(foo8,bl::norm_nfc,loc);
std::cout << "decomposed: " << deco.find("o") << ", composed: " << comp.find("o") <<"\n";

这给出:“分解:1,组成:3”。

现在,正确的答案取决于整理因子,但在大多数情况下,后者就是我想要的——o 的第一个位置,而不是分解的 ö 的第一部分。显然,对于这个示例,我可以将字符串规范化为 NFC,以确保获得所需的结果,但这对于无法组成字素簇的情况不起作用。

此外,X.find("ö") 将具有实现定义的行为,因为无法保证 ö 在搜索中如何编码。

我可以通过在 UAX 29 中实现算法或通过规范化搜索字符串来实现 Unicode 安全查找函数,但我想知道是否有办法通过使用 C++ std 库和 boost 来实现这一点 - 也许通过将语言环境与字符串算法相结合——但我还没有找到解决方案。

谁有明确的答案?我知道我可以使用 ICU,并且 boost::locale 是 ICU 库的 C++ 友好包装器(至少如果您想要完整的 unicode 支持的话)。

最佳答案

Further, X.find("ö") will have implementation defined behavior, as there are no guarentees how that ö is encoded in the search.

遗憾的是,您对此无能为力。作为 API 的客户端,您必须确保始终使用 u8 前缀调用它,并且参数也已标准化。人们可以编写一个 find 函数,在搜索之前对输入进行标准化,但无法减轻编码中的歧义。

I can implement a Unicode safe find function by implementing the algorithm in UAX 29

无需实现它,因为它已由 Boost.Locales segment_index 实现。

I'm wondering if there is a way to do this by using the C++ std library and boost -- perhaps by combining a locale with a string algorithm -- but I haven't found a solution.

标准库对此几乎毫无用处,据我所知,Boost.Locale 没有字符串搜索功能。 ICU 的字符串搜索功能使用规范等效的概念,这可能是您最好的选择。

关于c++ - 使用 boost 和标准 C++ 进行 Unicode 安全查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32866458/

相关文章:

python - Python xlsxwriter 库中的 UnicodeDecodeError

c++ - 类模板特化的运算符重载

c++ - 程序仅适用于包含(无副作用)cout 语句?

c++ - 编译器特定错误 : can't match function with const arguments

linux - Boost 智能阵列不起作用

javascript - 如何将用字体 A 编写的 unicode 字符串转换为字体 B?

c++ - Android 从 C++ 端播放原始音频

C++:对右值的 const 引用

c++ - 是否真的使用了使用指针类型实例化模板的能力?

javascript - 如何使用 ECMAScript 6 Unicode 代码点转义?