I need to split a line based on two separators: ' '
and ;
.
By example:
input : " abc ; def hij klm "
output: {"abc","def","hij","klm"}
How can I fix the function below to discard the first empty element?
std::vector<std::string> Split(std::string const& line) {
std::regex seps("[ ;]+");
std::sregex_token_iterator rit(line.begin(), line.end(), seps, -1);
return std::vector<std::string>(rit, std::sregex_token_iterator());
}
// input : " abc ; def hij klm "
// output: {"","abc","def","hij","klm"}
Below a complete sample that compiles:
#include <iostream>
#include <string>
#include <vector>
#include <regex>
std::vector<std::string> Split(std::string const& line) {
std::regex seps("[ ;]+");
std::sregex_token_iterator rit(line.begin(), line.end(), seps, -1);
return std::vector<std::string>(rit, std::sregex_token_iterator());
}
int main()
{
std::string line = " abc ; def hij klm ";
std::cout << "input: \"" << line << "\"" << std::endl;
auto collection = Split(line);
std::cout << "output: {";
auto bComma = false;
for (auto oneField : collection)
{
std::cout << (bComma ? "," : "") << "\"" << oneField << "\"";
bComma = true;
}
std::cout << "} " << std::endl;
}