Search code examples
c++dev-c++

How to count certain word in string using C++


How to counting the same word in a string

Input

Number of String

String1 = dadymathewdadreadad

String2 = sdgfghhjdjrjjyjjrtfdhe

Search = dad

Output

Number of dad in string1 = 3

Number of dad in string2 = 0

Code:

#include <iostream>
#include <string.h>

using namespace std;
int main() {

    string str[50];
    int n;

    cin>>n;

    for(int i = 0; i < n;i++) {
        cin>>str[i];
    }

    for(int i = 0; i < 50;i++) {
        if(substr(i,4) == "dad"){
            n += 1;
        }

    }
    cout<<n;
    return 0;
}

ERROR

In function 'int main()': [Error] 'substr' was not declared in this scope


Solution

  • Other Solution:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main(){
        int n; 
        string s[50];
        int c;
        cin>>n;
        for (int i=0;i<n;i++){
            cin>>s[i];
        }
        for (int i=0;i<n;i++) {
            c=0;
            int found=s[i].find("jack");
            while(found!=string::npos){
                found=s[i].find("jack",found+1);
                if(found) c++;
            }
            cout<<c<<endl;
        }
    }