C++ STL中没有类似Perl的split函数,必须自己写一个。下面是从网上(http://stackoverflow.com/questions/236129/c-how-to-split-a-string)
转帖的代码及使用方法,还是挺管用的。另外,C的strtok()函数也可以实现类似功能。
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } }
The tokenizer can be used in this way:
#include <string> #include <algorithm> #include <vector> using namespace std; int main() { vector<string> tokens; string str("Split me up! Word1 Word2 Word3."); Tokenize(str, tokens); copy(tokens.begin(), tokens.end(), ostream_iterator<string>(cout, ", ")); }