Last active
February 19, 2018 10:38
-
-
Save originalsouth/4f20fe69290834d64017ac7698756340 to your computer and use it in GitHub Desktop.
Split a delimited string into a vector of strings and apply a search and replace all on it
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 <cstdio> | |
#include <cstdlib> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
vector<string> splitter(const string &input,char delim=',') | |
{ | |
vector<string> retval; | |
const size_t I=input.size(); | |
size_t p,i; | |
for(p=0,i=0;i<I;i++) if(input[i]==delim and i+1<I) | |
{ | |
retval.push_back(input.substr(p,i-p)); | |
p=i+1; | |
} | |
if(p<i) | |
{ | |
string last=input.substr(p,i-p); | |
if(last.back()==delim) | |
{ | |
last.back()=0; | |
retval.push_back(last); | |
retval.push_back(""); | |
} | |
else retval.push_back(last); | |
} | |
return retval; | |
} | |
void replace_all(string &input,const string &search,const string &replace) | |
{ | |
for(size_t p=0;(p=input.find(search,p))!=string::npos;p+=replace.size()) input.replace(p,search.size(),replace); | |
} | |
int main() | |
{ | |
const string all="moo,boo,koo,loo,too"; | |
string input="doo,all,roo"; | |
replace_all(input,"all",all); | |
vector<string> vec=splitter(input); | |
for(string t:vec) printf("%s\n",t.c_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment