Finding words that begin with a given letter. - C++ STL

C++ examples for STL:string

Description

Finding words that begin with a given letter.

Demo Code

#include <iostream>
#include <iomanip>
#include <cctype>
#include <string>
#include <vector>

using std::string;

int main()//from   ww  w  . j ava2  s .co m
{
  string text{ "this is a test" };                                               // The text to be searched
  string letters{ "s" };

  const string separators{ " ,;:.\"!?'\n" };                    // Word  delimiters

  std::vector<string> words;                                   // Words found

  const int perline{ 5 };                                    // Words output per line

  int count{};                                             // Number of words found

  for (auto ch : letters)
  {
    unsigned int start{ text.find_first_not_of(separators) };
    int end{};
    string word;
    int max_length{};
    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);
      if (std::toupper(word[0]) == std::toupper(ch))
      {
        words.push_back(word);
        if (max_length < word.length()) max_length = word.length();
      }

      start = text.find_first_not_of(separators, end + 1);
    }
    // List words for current letter
    max_length += 2;
    std::cout << "\nWords beginning with '" << ch << "' are:\n";
    for (auto& word : words)
    {
      std::cout << std::setw(max_length) << std::left << word;
      if (++count % perline) continue;
      std::cout << std::endl;
    }
    std::cout << std::endl;
    words.clear();
    count = 0;
  }
}

Result


Related Tutorials