string c++

Write a program that will find the first occurance of the given keyword in the given text.
I have it displayed the symbol index and not index words, how to fix?
for example:
input: This is sentences
is
output: 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
using namespace std;

int main ()
{
   int index=0;
   string str;
   string key;
   getline(cin,str);
   getline(cin,key);
   index = str.rfind(key);

  cout <<index<<endl;
  return 0;
}
Well, by definition, if the search is successful, the word found must be the same as key. But you do need to check that the search was successful.

1
2
3
4
    if (index != string::npos)
    {
        cout << key << " was found at position " << index << endl;
    }


find the first occurance
note rfind() searches for the last, not first occurrence.
http://www.cplusplus.com/reference/string/string/rfind/
Last edited on
Topic archived. No new replies allowed.