Skip to content

Instantly share code, notes, and snippets.

@cleoold
Last active January 27, 2020 00:00
Show Gist options
  • Save cleoold/088c52efc1f26af5d0ad6d56fcaa2883 to your computer and use it in GitHub Desktop.
Save cleoold/088c52efc1f26af5d0ad6d56fcaa2883 to your computer and use it in GitHub Desktop.
C++ string join and split util
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
/** splits str into vector of substrings, str is not changed */
std::vector<std::string> StringSplit(std::string str, const std::string delim)
{
std::vector<std::string> res;
size_t pos;
while ((pos = str.find(delim)) != std::string::npos)
{
res.push_back(str.substr(0, pos));
str.erase(0, pos + delim.length());
}
res.push_back(str);
return res;
}
/** joins a vector of strings into a single string */
std::string StringJoin(const std::vector<std::string> &strs, const std::string delim)
{
if (strs.size() == 0) return "";
std::vector<char> res;
for (int i = 0; i < strs.size()-1; ++i)
{
for (auto c: strs[i]) res.push_back(c);
for (auto c: delim) res.push_back(c);
}
for (auto c: strs[strs.size()-1]) res.push_back(c);
return std::string{res.begin(), res.end()};
}
int main()
{
using SV = std::vector<std::string>;
assert
(StringSplit("", "+=+") == (SV{""}));
assert
(StringSplit("hello", "+=+") == (SV{"hello"}));
assert
(StringSplit("hello hewolli heilu ", " ") == (SV{"hello", "hewolli", "heilu", "", ""}));
assert
(StringSplit("hello+=+hweolli+=+heilu+=+h", "+=+") == (SV{"hello", "hweolli", "heilu", "h"}));
assert
(StringSplit("hello+=+hweolli+=+heilu+=+h", "++") == (SV{"hello+=+hweolli+=+heilu+=+h"}));
assert
(StringSplit("+=+hello+=+", "+=+") == (SV{"", "hello", ""}));
assert
(StringJoin(static_cast<const SV&>(SV{}), " ") == "");
assert
(StringJoin(static_cast<const SV&>(SV{""}), " ") == "");
assert
(StringJoin(static_cast<const SV&>(SV{"hello"}), " ") == "hello");
assert
(StringJoin(static_cast<const SV&>(SV{"hello", "hewolli", "heilu"}), " ") == "hello hewolli heilu");
assert
(StringJoin(static_cast<const SV&>(SV{"hello", "hewolli", "heilu", "", ""}), " ") == "hello hewolli heilu ");
std::puts("all tests passed!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment