将std::string中的迭代字符与unicode C++进行比较
Compare iterated character from std::string with 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;
}
...
- C++ - Unicode Newline
- 如何将unicode字符串从C++传递到delphi
- ascii 和 unicode 在处理级别有什么区别吗?
- 无法从 std::string 中提取C++ Unicode 符号
- MinGW64 - Unicode 源文件错误?
- 使用 Visual Studio 2019 编译 Unicode
- 将ANSI C字符串转换为UNICODE
- 如何从 oracle 数据库 c++ 读取 unicode
- 在特定 Unicode 路径中创建文件
- 如何存储 unicode 字符并将其输出到文件?
- C++ wmain 函数错误时使用 Unicode
- C++:打印 Unicode 字符
- QTextStream,用于打印英语和Unicode 16
- 将 unicode 字符串与 c ++ 符号进行比较?
- 如何在C++中使用 UTF-8 和 Unicode?C++20 char8_t有多大?
- 在 CHtmlEditCtrl::SetDocumentHTML 中使用 Unicode
- C++ - 为什么 unicode 输出不正确?
- 如何在 c++ 中读取用 utf-8 编码的 java unicode 字节字符串
- 在 Windows 中使用 boost::p rogram_options 从命令行参数读取 Unicode 字符
- C++:Unicode 字符串文字的可移植性