How to do std::string indexof in C++ that returns index of matching string?


Question

I'm looking for a string indexof function from the std namespace that returns an integer of a matching string similar to the java function of the same name. Something like:

std::string word = "bob";
int matchIndex = getAString().indexOf( word );

where getAString() is defined like this:

std::string getAString() { ... }
1
19
3/16/2009 6:06:05 PM

Accepted Answer

Try the find function.

Here is the example from the article I linked:

 string str1( "Alpha Beta Gamma Delta" );
 string::size_type loc = str1.find( "Omega", 0 );
 if( loc != string::npos ) {
   cout << "Found Omega at " << loc << endl;
 } else {
   cout << "Didn't find Omega" << endl;
 }
29
3/16/2009 6:41:56 PM

It's not clear from your example what String you're searching for "bob" in, but here's how to search for a substring in C++ using find.

string str1( "Alpha Beta Gamma Delta" );
string::size_type loc = str1.find( "Omega", 0 );

if( loc != string::npos )
{
   cout << "Found Omega at " << loc << endl;
}
else
{
   cout << "Didn't find Omega" << endl;
}

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon