Created
April 1, 2021 15:46
-
-
Save utilForever/196c37b01c1e4209ae0db8e1dedafc9d to your computer and use it in GitHub Desktop.
Split String in C++
This file contains hidden or 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
//! Splits a string \p str using \p delim. | |
//! \param str An original string. | |
//! \param delim A string delimiter to split. | |
//! \return A splitted string. | |
inline std::vector<std::string> SplitString(const std::string& str, | |
const std::string& delim) | |
{ | |
std::vector<std::string> tokens; | |
std::size_t prev = 0, pos; | |
do | |
{ | |
pos = str.find(delim, prev); | |
if (pos == std::string::npos) | |
{ | |
pos = str.length(); | |
} | |
std::string token = str.substr(prev, pos - prev); | |
if (!token.empty()) | |
{ | |
tokens.push_back(token); | |
} | |
prev = pos + delim.length(); | |
} while (pos < str.length() && prev < str.length()); | |
return tokens; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment