c++ - 如何检测 C++ 字符串中的 "_"?

标签 c++ string search find

我想知道“_”在字符串中的位置:

string str("BLA_BLABLA_BLA.txt");

类似于:

string::iterator it;
for ( it=str.begin() ; it < str.end(); it++ ){
 if (*it == "_")         //this goes wrong: pointer and integer comparison
 {
  pos(1) = it;
 }
 cout << *it << endl;
}

谢谢, 安德烈

最佳答案

请注意,"_" 是一个字符串文字,而'_' 是一个 字 rune 字

如果您将迭代器解引用为字符串,您得到的是一个字符。当然,字符只能和character literals比,不能和string 文字

但是,正如其他人已经注意到的那样,您不应该自己实现这样的算法。它已经完成了一百万次,其中两次(std::string::find()std::find())最终出现在 C++ 的标准库中。使用其中之一。

关于c++ - 如何检测 C++ 字符串中的 "_"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3725574/

相关文章:

c - 数组中内存的重新分配

string - PowerShell - 从字符串中选择特定行

python - 如何删除多个子串?

python - 在元组列表中查找值的更快方法是什么?

algorithm - 如果树是平衡的,在二叉搜索树中搜索的时间复杂度是多少?

c++ - 返回值中可以使用虚函数吗?

c++ - 如何安装 c++ 库以便我可以使用它?

c++ - vector Mat 的 opencv 切片

python - 我只想从测试文件中删除一个搜索行

c++ - 使用 C++11 type_traits 了解 Microsoft 的 _Is_duration