Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect "_" in a C++ string?

I want to know the positions of the "_" in a string:

string str("BLA_BLABLA_BLA.txt");

Something like:

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

Thanks, André

like image 315
andre de boer Avatar asked Sep 16 '10 10:09

andre de boer


3 Answers

Note that "_" is a string literal, while '_' is a character literal.

If you dereference an iterator into a string, what you get is a character. Of course, characters can only be compared to character literals, not to string literals.

However, as others have already noticed, you shouldn't implement such an algorithm yourself. It's been done a million times, two of which (std::string::find() and std::find()) ended up in C++' standard library. Use one of those.

like image 185
sbi Avatar answered Oct 06 '22 00:10

sbi


std::find(str.begin(), str.end(), '_');
                               // ^Single quote!
like image 20
aJ. Avatar answered Oct 05 '22 23:10

aJ.


string::find is your friend. http://www.cplusplus.com/reference/string/string/find/

someString.find('_');
like image 39
tauran Avatar answered Oct 05 '22 23:10

tauran