Searching a string for characters from a set - C++ STL

C++ examples for STL:string

Description

Searching a string for characters from a set

Demo Code

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

int main()//from  w ww .ja  v a2s. c o  m
{
  string text;                                           // The string 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;                             // Words found

  unsigned int start { text.find_first_not_of(separators) };   // First word start index
  unsigned int end {};                                         // Index for end of a word

  while (start != string::npos)                          // Find the words
  {
    end = text.find_first_of(separators, start + 1);     // Find end of word
    if (end == string::npos)                             // Found a separator?
      end = text.length();                               // No, so set to last + 1
    words.push_back(text.substr(start, end - start));    // Store the word
    start = text.find_first_not_of(separators, end + 1); // Find 1st character of next word
  }

  std::cout << "Your string contains the following " << words.size() << " words:\n";
  unsigned int count{};                                        // Number output
  for (const auto& word : words)
  {
    std::cout << std::setw(15) << word;
    if (!(++count % 5))
      std::cout << std::endl;
  }
  std::cout << std::endl;
}

Result


Related Tutorials