views:

276

answers:

5

Hello, 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é

+7  A: 

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

someString.find('_');
tauran
+5  A: 

You can make use of the find function as:

string str = "BLA_BLABLA_BLA.txt";
size_t pos = -1;

while( (pos=str.find("_",pos+1)) != string::npos) {
        cout<<"Found at position "<<pos<<endl;
}

Output:

Found at position 3
Found at position 10
codaddict
The answer is wrong. Regardless of whether you provide an initial position or not, the `std::string::find` will return the position *in the string*. The line `pos += found+1` should be changed to `pos = found+1`, and while you are at it, the whole `found` variable can be removed by initializing `pos` to `-1`, passing `pos+1` to `find` and storing the return value in `pos`. Try with "BLA_BLABLA_BLA_BLA.txt", it will only detect the first two '_'.
David Rodríguez - dribeas
@David: Thanks for pointing.
codaddict
+5  A: 

Why dont you use the find method : http://www.cplusplus.com/reference/string/string/find/

Benj
+7  A: 
std::find(str.begin(), str.end(), '_');
                               // ^Single quote!
aJ
+15  A: 
sbi
+1 for mentioning the *actual* problem he's having.
Dominic Rodger