C++ string get Frequency of words in text.

Description

C++ string get Frequency of words in text.

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using std::string;

int main()// w  ww.  j  a  v a 2 s .  c  om
{
  string text;                                               // The text to be searched
  std::cout << "Enter some text terminated by *:\n";
  std::getline(std::cin, text, '*');

  const string separators {" ,;:.\"!?'\n"};                  // Word  delimiters
  std::vector<string> words;
  std::vector<int> counts;

  int start {text.find_first_not_of(separators)};
  int end {};
  string word;
  bool is_in {false};

  while (start != string::npos){
    end = text.find_first_of(separators, start + 1);

    if (end == string::npos)
      end = text.length();

    word = text.substr(start, end - start);

    is_in = false;

    for (int i {}; i < words.size(); ++i){
      if (words[i] == word){
        ++counts[i];
        is_in = true;
        break;
      }
    }
    if (!is_in)
    {
      words.push_back(word);
      counts.push_back(1);
    }
    start = text.find_first_not_of(separators, end + 1);
  }

  int max_length {};
  for (auto& word : words){
    if (max_length < word.length())
       max_length = word.length();
  }

  std::cout << "Your string contains the following " << words.size() << " words and counts:\n";

  int count {};                                            // Numbers of words output

  const int perline {3};                                   // Number per line

  for (int i {}; i < words.size(); ++i){
    std::cout << std::setw(max_length) << std::left << words[i] << std::setw(4) << std::right << counts[i] << "  ";
    if (!(++count % perline))
      std::cout << std::endl;
  }
  std::cout << std::endl;
}



PreviousNext

Related