Skip to content

Instantly share code, notes, and snippets.

@R3D9477
Created May 11, 2021 15:10
Show Gist options
  • Save R3D9477/6fcc9e3ffadf20a7d822471178fa0e10 to your computer and use it in GitHub Desktop.
Save R3D9477/6fcc9e3ffadf20a7d822471178fa0e10 to your computer and use it in GitHub Desktop.
C++ std::string split ( + remove_empty )
#pragma once
#include <vector>
#include <string>
#include <sstream>
auto split (const std::string& line, char seperator, bool remove_empty = false)
{
std::vector<std::string> strs;
std::string::size_type prev_pos = 0, pos = 0;
while ((pos = line.find(seperator, pos)) != std::string::npos)
{
std::string substring( line.substr(prev_pos, pos-prev_pos) );
if (remove_empty)
{
std::stringstream(substring) >> substring;
if (substring.size() > 0) strs.push_back(substring);
}
else strs.push_back(substring);
prev_pos = ++pos;
}
auto lw = line.substr(prev_pos, pos-prev_pos);
if (remove_empty)
{
std::stringstream(lw) >> lw;
if (lw.size() > 0) strs.push_back(lw);
}
else strs.push_back(lw);
return strs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment