Skip to content

Instantly share code, notes, and snippets.

@microtherion
Created August 10, 2015 21:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save microtherion/28f034580d25945be586 to your computer and use it in GitHub Desktop.
Save microtherion/28f034580d25945be586 to your computer and use it in GitHub Desktop.
Implement C++ equivalent of ObjC componentsSeparatedByString:
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
template <typename String, typename OutputIt>
void components_separated_by_string(const String & string, const String & separator, OutputIt out)
{
typename String::size_type comp_start=0, comp_end;
while ((comp_end = string.find(separator, comp_start)) != String::npos) {
*out++ = string.substr(comp_start, comp_end-comp_start);
comp_start = comp_end+separator.size();
}
if (comp_start || string.size())
*out++ = string.substr(comp_start);
}
template <typename String, typename OutputContainer=std::vector<String>>
OutputContainer components_separated_by_string(const String & string, const String & separator)
{
OutputContainer container;
components_separated_by_string(string, separator, std::back_inserter(container));
return container;
}
int
main(int, char **)
{
auto components = components_separated_by_string<std::string>("Blue meanies are blue", " ");
for (const std::string comp : components)
std::cout << comp << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment