On Thu, 24 Feb 2005 06:24:31 GMT, "Kelvin@!!!"
<ch******************@yahoo.com.hk.hk> wrote:
hi:
in C, we can use strtok() to tokenize a char*
but i can't find any similar member function of string that can tokenize a
string
so how so i tokenize a string in C++?
do it the C way?
thanks
There is a sample chapter from Accelerated C++ on the web at
http://www.awprofessional.com/articl...le.asp?p=25333
The chapter has a function called split() which does what you seem to
want, it takes a string and returns a vector of all the individual
words:
// true if the argument is whitespace, false otherwise
bool space(char c) { return isspace(c); }
// false if the argument is whitespace, true otherwise
bool not_space(char c) { return !isspace(c); }
vector<string> split(const string& str) {
typedef string::const_iterator iter;
vector<string> ret;
iter i = str.begin();
while (i != str.end()) {
// ignore leading blanks
i = find_if(i, str.end(), not_space);
// find end of next word
iter j = find_if(i, str.end(), space);
// copy the characters in [i, j)
if (i != str.end()) ret.push_back(string(i, j));
i = j;
}
return ret;
}
There is a detailed explanation of the functino in the text.
rossum
--
The ultimate truth is that there is no Ultimate Truth