TITLE: word counting example using STL (Newsgroups: comp.lang.c++, 24 May 2000) STRANGWICK: (craig_strangwick@hotmail.com) : 1. words are completeley made of alphabetic, numeric, hyphens : and apostrophe's. KUEHL: dietmar.kuehl@claas-solutions.de OK, this is easy to accomplish. STRANGWICK: : 2. apostrophe's appearing before AND after a word should be : ignored. KUEHL: That is, individual apostrophe's like in "a ' a" should not count as a word but embedded apostrophe's like in "don't" should not separate words, is this correct? Probably the same applies to hyphens. Here is the trivial code: #include #include #include #include class space_ctype: public std::ctype { public: space_ctype(): std::ctype(get_table()) {} private: static void set_space(std::ctype_base::mask& c) { c |= space; } static std::ctype_base::mask* get_table() { static std::ctype_base::mask rc[table_size]; std::copy(classic_table(), classic_table() + table_size, rc); std::for_each(rc, rc + table_size, set_space); static char letters[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789-'"; for (char* tmp = letters; tmp != letters + sizeof(letters); ) rc[*tmp++] &= ~space; return rc; } }; int main() { std::locale l; std::locale new_l(l, new space_ctype); std::cin.imbue(new_l); std::string str; int count = 0; while (std::cin >> str) if (str.find_first_not_of("-'") != str.npos) ++count; std::cout << "words: " << count << "\n"; } If there wasn't this restriction with respect to hyphens and apostrophe's, the code would be somewhat simpler: The "if" could be dropped :-) _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com