Split Strings in C++ With Boost
I just wrote about how to trim strings with boost. The code where I first needed to trim a string, was actually very simple naive parser where strings of key value pairs would be split, and then each part trimmed to ensure that both key and value was without leading and trailing whitespace. When you want to split a string in c++ you again probably want to use the boost library - more specifically boost/algorithm/string/split.hpp. This allows you to split a string by a character (or rather a substring) into a vector of strings.
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
int main() {
std::string result;
std::string str01 = "this,is,a,list,of,words";
std::vector<std::string> parts;
boost::split(parts , str01, boost::is_any_of(","));
for (std::vector<std::string>::const_iterator i = parts.begin(); i != parts.end(); ++i)
std::cout << *i << std::endl;
return 0;
}
Like last time the progam is compiled using clang++ -std=c++0x -stdlib=libc++ test.cpp -o test
and then run by calling ./test
The output should be:
this
is
a
list
of
words