2010-09-16 109 views
5

我想知道在字符串中的 “_” 的位置:如何检测C++字符串中的“_”?

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

感谢, 安德烈

+5

尝试使用单引号而不是双引号。 – 2010-09-16 10:06:58

+0

@多米尼克为什么不是这个答案? – Motti 2010-09-16 10:34:39

+0

@Motti - 现在是(见sbi的答案http://stackoverflow.com/questions/3725574/detect-in-a-string/3725671#3725671) – 2010-09-16 10:47:39

回答

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 
+0

答案是错误的。无论您是否提供初始位置,std :: string :: find都会返回字符串*中的位置*。 'pos + = found + 1'这一行应该改为'pos = found + 1',而当你在它的时候,整个'found'变量可以通过将'pos'初始化为'-1' 'pos + 1'到'find'并将返回值存储在'pos'中。尝试使用“BLA_BLABLA_BLA_BLA.txt”,它只会检测前两个'_'。 – 2010-09-16 10:41:47

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

注意"_"字符串字面,而'_'字符文字

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

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

+2

+1提到他有*实际*问题。 – 2010-09-16 10:22:36