// strtok.cpp - STLized strtok // Marcus Fritzsch, http://fritschy.de, 2006-04-21 #include #include #include #include #include #include class StringTok { private: class TokSeparator : public std::unary_function { public: std::string sep; std::vector tok; TokSeparator (const std::string & s) : sep (s), tok () { tok.push_back (""); } void operator () (const char & c) { if (std::find (sep.begin (), sep.end (), c) == sep.end ()) tok.back () += c; else if (tok.back ().length ()) tok.push_back (""); } }; std::vector t; public: StringTok (const std::string & str, const std::string & sep) : t () { t = std::for_each (str.begin (), str.end (), TokSeparator (sep)).tok; } // XXX: devilish! operator std::vector () { return t; } }; int main () { std::string theStr = "abc:xyz:012:-)"; std::string theSep = ":-"; std::vector tokens = StringTok (theStr, theSep); std::copy (tokens.begin (), tokens.end (), std::ostream_iterator (std::cout, "\n")); return 0; }