Skip to content

Instantly share code, notes, and snippets.

@bwedding
Created December 6, 2021 22:48
Show Gist options
  • Save bwedding/65dc726f2d0fc612ce21408ad8039c53 to your computer and use it in GitHub Desktop.
Save bwedding/65dc726f2d0fc612ce21408ad8039c53 to your computer and use it in GitHub Desktop.
C++ version of C# Split(). Splits a string with multiple delimiters into a std::vector<std::string>
// StringSplitter.cpp
#include <iostream> // std::cout
#include <vector> // std::vector
#include <fstream>
std::vector<std::string> Split(const std::string str, const std::vector<std::string> delims)
{
const std::string fixedDelim = ",";
std::vector<std::string> split;
size_t t = 0;
// Make a copy of the string
std::string tmp = str;
// First, replace all delimeters with a common delimeter
for (const auto& delim : delims)
{
t = 0;
while (( t = tmp.find(delim, t)) != std::string::npos)
{
tmp = tmp.replace(t, delim.size(), fixedDelim);
t += delim.size();
}
}
t = 0;
int start = 0;
// Extract all delimited values
while ((t = tmp.find(fixedDelim, t)) != std::string::npos)
{
split.push_back(tmp.substr(start, t - start));
start = t + 1;
t += fixedDelim.size() + 1;
}
return split;
}
int main()
{
std::string input = "123,456->789,654->843*579-1289";
std::cout << "String to parse:\n" << input << "\n";
auto val = Split(input, { ",", "->", "*", "-"});
std::cout << "Split returned:\n";
for (auto str : val)
std::cout << str << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment