Extract Sentences from a Vector of Characters - C++ STL

C++ examples for STL:vector

Description

Extract Sentences from a Vector of Characters

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cctype>
using namespace std;
bool is_sentence_start(char ch);
template<class InIter>
void show_range(const char *msg, InIter start, InIter end);
int main()/*w w w  . j  a  va2  s .  c o  m*/
{
   vector<char> v;
   vector<char>::iterator itr;
   const char *str = "This is a test? Yes, it is! This too.";
   for(unsigned i=0; i < strlen(str); i++)
      v.push_back(str[i]);
   show_range("Contents of v: ", v.begin(), v.end());
   cout << endl;
   // Find the beginning of all sentences.
   cout << "Use find_if() to display each sentence in v:\n";


   vector<char>::iterator itr_start, itr_end;
   itr_start = v.begin();
   do {

      itr_start = find_if(itr_start, v.end(), is_sentence_start);

      itr_end = find_if(itr_start, v.end(), is_sentence_start);

      show_range("", itr_start, itr_end);
   } while(itr_end != v.end());
   return 0;
}
// Return true if ch is the first letter in a sentence.
bool is_sentence_start(char ch) {
   static bool endofsentence = true;
   if(isalpha(ch) && endofsentence ) {
      endofsentence = false;
      return true;
   }
   if(ch=='.' || ch=='?' || ch=='!') endofsentence = true;
   return false;
}
// Show a range of elements.
template<class InIter>
void show_range(const char *msg, InIter start, InIter end) {
   InIter itr;
   cout << msg;
   for(itr = start; itr != end; ++itr)
      cout << *itr;
   cout << endl;
}

Result


Related Tutorials