#include #include #include #include using namespace std; namespace { /** * This function splits s based on the characters in * the separators string. The individual parts of * the split string are returned to the caller through * parts.

* * The allow_empty_parts boolean determines whether * this function inserts empty strings to indicate that one * separator directly followed another without any non-separator * characters in the middle. If this boolean is set to * false, any sequence of separators in * s will be treated as just a single separator.

* * @param[out] parts parts of strings * @param[in] s string to split * @param[in] allow_empty_parts whether to allow empty parts * @param[in] separators string of characters that separate parts */ void split(vector& parts, const string& s, bool allow_empty_parts = false, const char* separators = " \t\r\n\f\v") { vector::size_type start = 0; vector::size_type end = 0; parts.clear(); do { end = s.find_first_of(separators, start); if (end == string::npos) { /* No match. */ break; } if (allow_empty_parts || (start < end)) { parts.push_back(s.substr(start, end - start)); } start = end + 1; } while (start < s.length()); /* There is always an implicit match at the end of the string. */ if (start < s.length()) { parts.push_back(s.substr(start)); } /* There is always an empty match at the end of the string if * we are allowing empty parts and the string ended with a * separator. This way assuming "|" is your string of * separator characters, "foo|bar|baz" and "foo|bar|" will * both return three parts where it appears that "baz" was * intentionally left empty. */ if (allow_empty_parts && (end == s.length() - 1)) { parts.push_back(""); } } /** * This function joins the vector of strings v * placing the delimiting character delim between * each string. The joined string is returned to the caller. * * @param[in] v vector of strings to join * @param[in] delim delimiting character inserted between each string * @return joined string */ string join(const vector& v, char delim = ' ') { string rv; for (unsigned i = 0 ; i < v.size() ; ++i) { if (i > 0) { rv += delim; } rv += v[i]; } return rv; } } int main(int argc, char* argv[]) { int rv = 0; string line; try { while (getline(cin, line)) { cout << "line = \"" << line << "\"" << endl; vector elements; split(elements, line); for (unsigned i = 0 ; i < elements.size() ; ++i) { cout << " elements[" << i << "] = \"" << elements[i] << "\"" << endl; } cout << " join(elements) = \"" << join(elements) << "\"" << endl; } } catch (const exception& e) { cerr << "*** Error: " << e.what() << endl; rv = 1; } return rv; }