Created
September 24, 2018 08:03
-
-
Save leira/5525963b7ad9c8bf3b49b604c4a9fe97 to your computer and use it in GitHub Desktop.
C++ string split and join
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
| #include <string> | |
| #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN | |
| #include "doctest.h" | |
| std::vector<std::string> split(std::string const& str, std::string const& delim) | |
| { | |
| std::vector<std::string> tokens; | |
| std::string::size_type s = 0; | |
| std::string::size_type e = str.find(delim, s); | |
| while (e != std::string::npos) { | |
| tokens.emplace_back(str.substr(s, e - s)); | |
| s = e + delim.length(); | |
| e = str.find(delim, s); | |
| } | |
| tokens.emplace_back(str.substr(s, e - s)); | |
| return tokens; | |
| } | |
| std::string join(std::vector<std::string> const& strs, std::string const& delim) | |
| { | |
| std::string ss; | |
| for (auto const& s : strs) { | |
| ss += ss.empty() ? s : delim + s; | |
| } | |
| return ss; | |
| } | |
| TEST_CASE("Split string with delimiter") { | |
| std::string s1 = "12, 23, 34"; | |
| CHECK(split(s1, ", ") == std::vector<std::string>{"12", "23", "34"}); | |
| CHECK(join(split(s1, ", "), ", ") == s1); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment