2010-09-16 83 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