Frequency of words in text. - C++ STL

C++ examples for STL:vector

Description

Frequency of words in text.

Demo Code

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

int main()/*from  w w  w. j  a  v a 2s .c o m*/
{
  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;

  unsigned 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 (unsigned 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);
  }

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

Result


Related Tutorials