Splitting a string by a character
Another way (C++11/boost) for people who like RegEx. Personally I'm a big fan of RegEx for this kind of data. IMO it's far more powerful than simply splitting strings using a delimiter since you can choose to be be a lot smarter about what constitutes "valid" data if you wish.
#include <string>
#include <algorithm> // copy
#include <iterator> // back_inserter
#include <regex> // regex, sregex_token_iterator
#include <vector>
int main()
{
std::string str = "08/04/2012";
std::vector<std::string> tokens;
std::regex re("\\d+");
//start/end points of tokens in str
std::sregex_token_iterator
begin(str.begin(), str.end(), re),
end;
std::copy(begin, end, std::back_inserter(tokens));
}
Using vectors, strings and stringstream. A tad cumbersome but it does the trick.
#include <string>
#include <vector>
#include <sstream>
std::stringstream test("this_is_a_test_string");
std::string segment;
std::vector<std::string> seglist;
while(std::getline(test, segment, '_'))
{
seglist.push_back(segment);
}
Which results in a vector with the same contents as
std::vector<std::string> seglist{ "this", "is", "a", "test", "string" };
Boost has the split() you are seeking in algorithm/string.hpp
:
std::string sample = "07/3/2011";
std::vector<std::string> strs;
boost::split(strs, sample, boost::is_any_of("/"));
Since nobody has posted this yet: The c++20 solution is very simple using ranges
. You can use a std::ranges::views::split
to break up the input, and then transform the input into std::string
or std::string_view
elements.
#include <ranges>
...
// The input to transform
const auto str = std::string{"Hello World"};
// Function to transform a range into a std::string
// Replace this with 'std::string_view' to make it a view instead.
auto to_string = [](auto&& r) -> std::string {
const auto data = &*r.begin();
const auto size = static_cast<std::size_t>(std::ranges::distance(r));
return std::string{data, size};
};
const auto range = str |
std::ranges::views::split(' ') |
std::ranges::views::transform(to_string);
for (auto&& token : str | range) {
// each 'token' is the split string
}
This approach can realistically compose into just about anything, even a simple split
function that returns a std::vector<std::string>
:
auto split(const std::string& str, char delimiter) -> std::vector<std::string>
{
const auto range = str |
std::ranges::views::split(delimiter) |
std::ranges::views::transform(to_string);
return {std::ranges::begin(range), std::ranges::end(range)};
}
Live Example