Created
August 10, 2015 21:18
-
-
Save microtherion/28f034580d25945be586 to your computer and use it in GitHub Desktop.
Implement C++ equivalent of ObjC componentsSeparatedByString:
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 <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