Skip to content

Instantly share code, notes, and snippets.

@uliwitness
Created August 10, 2015 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uliwitness/8fd60ecfc269c330cd29 to your computer and use it in GitHub Desktop.
Save uliwitness/8fd60ecfc269c330cd29 to your computer and use it in GitHub Desktop.
I'm a bit surprised C++ doesn't have an equivalent to Objective C's componentsSeparatedByString, but it's easy enough to roll your own, I suppose.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> components_separated_by_string( const string& s, const string& delimiter )
{
if( s.size() == 0 )
return vector<string>();
size_t last = 0;
size_t next = 0;
vector<string> components;
while ((next = s.find(delimiter, last)) != string::npos)
{
components.push_back( s.substr(last, next-last) );
last = next + 1;
}
components.push_back( s.substr(last) );
return components;
}
int main(int argc, char *argv[])
{
vector<string> components = components_separated_by_string("Blue,Meanies,Rule,The,eWorld",",");
for( string currStr : components )
cout << currStr << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment