I need to display how many times does the last word appear in a string

Viewed 40

For example, if I have "dog cat person car person house person", the word "person" appears 3 times, so the program should display 3. I've tried:

    char s[51],*p,sep[]=" ,.",s1[21];
    int nr=51,k=1;
    cin.get(s,51);
    p=strtok(s,sep);
    while(p)
    {
        nr--;
        if (nr==1) strcpy(s1,p);
        else
        if(strcmp(s1,p)==0) k++;
        p=strtok(NULL,sep);
    }
    cout<<k;

I resolved a similar problem, but I had to display how many times the first word appeared in the string, so I thought this should be the same, just with some small changes, but this code doesn't seem to work. What did I do wrong? Or what should I change?

1 Answers

Just keep track of the counts of each word, and remember the count of the last word as you go.

#include <iostream>
#include <map>
#include <string>

using std::cin;
using std::cout;
using std::map;
using std::string;

int main() {
    string word;
    auto last_tally = 0;
    map<string, int> word_tally;

    while (cin >> word) {
        last_tally = ++word_tally[word];
    }

    cout << last_tally << "\n";
}
Related