如何在C++字符串中检测"_"?

and*_*oer 5 c++ string search find

我想知道字符串中"_"的位置:

string str("BLA_BLABLA_BLA.txt");
Run Code Online (Sandbox Code Playgroud)

就像是:

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢,安德烈

sbi*_*sbi 16

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

如果您将迭代器取消引用到字符串中,您获得的是一个字符.当然,字符只能与字符文字进行比较,而不能与字符串文字进行比较.

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

  • +1提及他所遇到的*实际*问题. (2认同)

aJ.*_*aJ. 9

std::find(str.begin(), str.end(), '_');
                               // ^Single quote!
Run Code Online (Sandbox Code Playgroud)


cod*_*ict 6

您可以将该find功能用作:

string str = "BLA_BLABLA_BLA.txt";
size_t pos = -1;

while( (pos=str.find("_",pos+1)) != string::npos) {
        cout<<"Found at position "<<pos<<endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Found at position 3
Found at position 10
Run Code Online (Sandbox Code Playgroud)