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++的标准库.使用其中之一.
string :: find是你的朋友. http://www.cplusplus.com/reference/string/string/find/
someString.find('_');
Run Code Online (Sandbox Code Playgroud)
您可以将该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)