将std::string中的迭代字符与unicode C++进行比较



我已经为这个问题挣扎了很长一段时间,这是我第一次处理unicode或UTF-8。

这就是我要做的,我只想迭代一个std::字符串,该字符串包含普通字母表和unicode符号的组合,在我的情况下,它是短划线"–"。更多信息:http://www.fileformat.info/info/unicode/char/2013/index.htm

这是我尝试过的代码,但它不会运行:

#include <iostream>
#include <string>
int main()
{
std::string str = "test string with symbol – and !";
for (auto &letter : str) {
if (letter == "–") {
std::cout << "found!" << std::endl;
}
}
return 0;
}

这是我的编译器的结果:

main.cpp: In function 'int main()':
main.cpp:18:23: error: ISO C++ forbids comparison between pointer and 
integer [-fpermissive]
if (letter == "–") {
^

此外,当我浏览互联网时,我发现了一个有趣的信息,我需要解决这类任务。如何在c++字符串中搜索非ASCII字符?

但当我试图用UTF-8十六进制代码修改我的代码时,它也不会运行:

if (letter == "xE2x80x93") {
std::cout << "found!" << std::endl;
}

来自我的编译器的消息完全相同,即c++禁止在指针和整数之间进行比较。

我错过什么了吗?或者我需要使用像ICU或Boost这样的库吗?非常感谢你的帮助。非常感谢。

更新

根据邪恶羊的回答,我一直在改进我的代码,但它仍然无法工作。它可以通过编译,但当我尝试运行它时,它无法输出"find!"。那么,我该如何解决这个问题呢?非常感谢。

这段代码怎么样?

#include <iostream>
#include <string>
int main()
{
std::wstring str = L"test string with symbol – and !";
for (auto &letter : str) {
if (letter == L'–') {
std::cout << "found!" << std::endl;
}
}
return 0;
}

正如UnholySheep在评论中所说,字符文字"–"是一个字符数组。假设使用utf8表示,则char em_dash = "–";char em_dash = {'xe2', 'x80', 'x93'};相同。

您只能使用当前代码找到真正的字符。例如,这将正确工作:

...
if (letter == '!')
...

因为CCD_ 4是一个字符常数。

如果你只想在基本多语言平面中处理unicode字符(代码低于0xFFFF),那么使用宽字符就足够了,正如@ArashMohammadi的回答中所建议的那样。对于类似BMP的表情符号字符之外的字符,另一种解决方案是使用std::u32string,其中每个unicode字符都由一个char32_t字符表示。

如果您想直接处理单字节字符的UTF8编码字符串,则必须使用compare方法:

std::string em_dash = "–"; // or "xe2x80x93"
...
for (size_t pos=0; pos <= str.size() - em_dash.size(); pos++) {
if (str.compare(pos, em_dash.size(), em_dash()) == 0) {
std::cout << "found!" << std::endl;
}
}
...

或者直接使用find方法:

...
if (str.find(em_dash) != str.npos) {
std::cout << "found!" << std::endl;
}
...

最新更新