Hana
Hana

Reputation: 81

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

Upvotes: 0

Views: 962

Answers (3)

Hana
Hana

Reputation: 81

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;
    }
}

Upvotes: 0

jignatius
jignatius

Reputation: 6474

You can use the find() member function of std::string, adjusting the start position after every successful find until the end of the string:

#include <string>

int count(const std::string& sentence, const std::string& word)
{
    int total = 0;
    size_t start = 0;
    size_t pos = 0;

    while ((pos = sentence.find(word, start)) != std::string::npos)
    {
        ++total;
        start = pos + word.size();
    }

    return total;
}

int main()
{
    std::string input = "dadymathewdadreadady";
    int c = count(input, "dad");
    return 0;
}

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

One trick you could use here would be to just replace the search term (e.g. dad) with empty string, and then compare the length of the string before and after the replacement.

string input = "dadymathewdadreadady";
string search = "dad";
int size_orig = input.size();
replace(string, search, "");
cout << "number of 'dad' is: " << (size_orig - input.size()) / search.size();

Upvotes: 2

Related Questions