24

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() { ... }
Alex B
  • 24,678
  • 14
  • 64
  • 87

4 Answers4

35

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;
 }
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
  • 1
    Is there a function for actually finding the _index_ at which the substring begins? I could subtract the beginning iterator, but is that necessary? – Arnav Borborah Oct 26 '17 at 14:16
  • @ArnavBorborah `find` returns the index. The unsigned integer type `string::size_type` is just there to guarantee that the result of `find` fits into `loc`. (Think a really, really big index might not fit into an `int`.) https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int – Robert Mar 01 '20 at 16:41
5

You are looking for the std::basic_string<> function template:

size_type find(const basic_string& s, size_type pos = 0) const;

This returns the index or std::string::npos if the string is not found.

dirkgently
  • 108,024
  • 16
  • 131
  • 187
5

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;
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

I'm not exactly sure what your example means, but for the stl string class, look into find and rfind

Perchik
  • 5,262
  • 1
  • 19
  • 22