Created
May 11, 2021 15:10
-
-
Save R3D9477/6fcc9e3ffadf20a7d822471178fa0e10 to your computer and use it in GitHub Desktop.
C++ std::string split ( + remove_empty )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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