javakook javakook - 2 months ago 10
C++ Question

How to count number of times word is repeated in C++

Hi I am having some trouble with this code.

I am supposed to write a program that takes in lines of text and breaks the letters into words, counts the number of times the unique word appears. I am having trouble with sorting thru the vector to count the number of time each word is repeated in the input.

I am trying to implement the bubble sort method to do so, if somebody could show me and example of how to implement the bubble sort method in my code that would be very helpful Thank you.

Here is the part of my code I'm stuck on.

vector<string> split(string s) {
vector<string> strings;
string substring;
int i = 0;
int j = s.find(' ');

while (j != string::npos) {
substring = clean_string(s.substr(i, j-i));

if(substring.size() > 0) {
strings.push_back(substring);
}
i = ++j;
j = s.find(' ', j);

if (j == string::npos)
{
substring = clean_string(s.substr(i, s.length()));
if(substring.size() > 0) {
strings.push_back(substring);
}
}
}
return strings;
}
for(int i =0;i = clean_string.length(); i++ ){ // trying to starting to count number of words repeats

}

string clean_string(string s) {
while(s.back() == '.'
|| s.back() == ','
|| s.back() == '!'
|| s.back() == '\'') {
s.pop_back();
}
return s;

}

Answer

Bubble sort:

vector<string> strings = split(str);
for (int i = 0; i < strings.size(); i++) {
    for (int j = 0; j < strings.size() - 1; j++) {
        if (strings[j + 1] < strings[j]) {
            string tmp = strings[j];
            strings[j] = strings[j + 1];
            strings[j + 1] = tmp;
        }
   }
}

Counting words after ordering:

string prev = strings[0];
int counter = 1;

for (int i = 1; i < strings.size(); i++) {
    if (strings[i] == prev) {
        counter++;
    } else {
        cout << prev << ": " << counter << " ";
        prev = strings[i];
        counter = 1;
    }
}