![]() |
"split" function
Is there a C++ or C standard library function that splits an std::string (or char*) into words, based on a certain delimiter? What I'm looking for is something like this:
at the beginning, line == "the big blue dog ate food." words is an array of std::strings whatever_function(line,words,' '); at the end, words should equal {"the","big","blue","dog","ate","food"} |
strtok can work for you.
|
:
int main(int argc, char* argv[]) |
No, not to my knowledge. Unfortunately strtok only works with single character delimiters and it takes a const char pointer argument instead of a std::string. The less const char pointers I see in my code, the happier I tend to be :P. You can also use std::getline to do this, but again that takes a single char as a delimiter.
Here's the simple function I wrote to do this. :
// Returns a std::vector of the split strings:
int main() { |
Strtok takes multiple delimiters, but it is intended for use with arrays of char, not std strings. Furthermore, it alters the original, so even where one can use it, one may need to copy the original first. When PHP nabbed it as a utility, they burned off some of the warts.
|
ok
getline + istringstream seems to be what I'm looking for. Thanks all! |
I would say boost/algorithm/string/split.hpp is what u need. its still no standart functions , but a lot of the boost libs will become standart in the 0x10 c++ standart and i m pretty sure that the string-algo lib will...
btw boost is so powerfull u should have a look or even learn to handle some parts. like boost::split the function gets a sequence,a collection and a prdicate, and an so called token compress mode type, but u dont need that one. so for your purposes it would look like this :
template<typename SequenceSequenceT, typename CollectionT, :
split(SequenceSequenceT &, CollectionT &, PredicateT);id just wrote this little testmain. i think its exactly what you ask for: :
#include<iostream>:
your wish:can use it on every containers convertable to each other. |
Quote:
|
The problem posted by OP is so simple -- Forget about using all those other complex templates that do nothing more than make the solution to the problem more complicated. You guys are making such a complicated solution out of something that is very trivel. :eek:
|
Quote:
|
| All times are GMT -5. The time now is 4:27 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC