Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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() { ... } 
like image 835
Alex B Avatar asked Mar 16 '09 17:03

Alex B


People also ask

How do you find the index of a string in another string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the index of a character in a string?

To get the index of a character's last occurrence in a string, you use the lastIndexOf() method, passing it the specific character as a parameter. This method returns the index of the last occurrence of the character or -1 if the character is not found.


2 Answers

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;  } 
like image 143
Andrew Hare Avatar answered Sep 18 '22 12:09

Andrew Hare


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; } 
like image 25
Bill the Lizard Avatar answered Sep 18 '22 12:09

Bill the Lizard