Java has a convenient split method:
String str = "The quick brown fox";
String[] results = str.split(" ");
Is there an easy way to do this in C++?
Java has a convenient split method:
String str = "The quick brown fox";
String[] results = str.split(" ");
Is there an easy way to do this in C++?
I know you asked for a C++ solution, but you might consider this helpful:
Qt
The advantage over Boost in this example is that it's a direct one to one mapping to your post's code.
See more at Qt documentation
Here's an approach that allows you control over whether empty tokens are included (like strsep) or excluded (like strtok).
There is no direct way to do this. Refer this code project source code to find out how to build a class for this.
MFC/ATL has a very nice tokenizer. From MSDN:
Your simple case can easily be built using the
std::string::find
method. However, take a look at Boost.Tokenizer. It's great. Boost generally has some very cool string tools.Seems odd to me that with all us speed conscious nerds here on SO no one has presented a version that uses a compile time generated look up table for the delimiter (example implementation further down). Using a look up table and iterators should beat std::regex in efficiency, if you don't need to beat regex, just use it, its standard as of C++11 and super flexible.
Some have suggested regex already but for the noobs here is a packaged example that should do exactly what the OP expects:
If we need to be faster and accept the constraint that all chars must be 8 bits we can make a look up table at compile time using metaprogramming:
With that in place making a
getNextToken
function is easy:Using it is also easy:
Here is a live example: http://ideone.com/GKtkLQ