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

5

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

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;
}

感谢您,André。

5
尝试使用单引号代替双引号。 - Dominic Rodger
@Dominic,为什么这不是一个答案? - Motti
@Motti - 现在是这样的(请参见sbi的答案https://dev59.com/RlDTa4cB1Zd3GeqPJoO7#3725671) - Dominic Rodger
5个回答

16
请注意,"_"是一个字符串字面量,而'_'则是一个字符字面量
如果您将迭代器解引用为字符串,则获得的是一个字符。当然,字符只能与字符字面量进行比较,而不能与字符串字面量进行比较。
但是,正如其他人已经注意到的那样,您不应该自己实现这样的算法。它已经被做了无数次,其中两个 (std::string::find()std::find()) 已经被放入 C++ 的标准库中。使用其中的一个即可。

9
std::find(str.begin(), str.end(), '_');
                               // ^Single quote!

8

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;
}

输出:

Found at position 3
Found at position 10

答案是错误的。无论您是否提供初始位置,std::string::find都会返回字符串中的位置。将pos += found+1这一行更改为pos = found+1,并且在此过程中,可以通过将pos初始化为-1,将pos+1传递给find并将返回值存储在pos中来删除整个found变量。尝试使用"BLA_BLABLA_BLA_BLA.txt"进行测试,它只会检测到前两个'_'。 - David Rodríguez - dribeas

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接