Skip to content

Instantly share code, notes, and snippets.

@RashidLadj
Created September 6, 2021 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RashidLadj/029c4206817b45fc7a5eb1b3bdd6c427 to your computer and use it in GitHub Desktop.
Save RashidLadj/029c4206817b45fc7a5eb1b3bdd6c427 to your computer and use it in GitHub Desktop.
implementation of a simple function which is used to split a character string by taking the delimiter
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split (const string &s, const string &delimiter);
int main() {
string myString = "We_try_to_split_string";
vector<string> items = split(myString, "_");
for (const auto &x : items)
cout << x << endl;
}
vector<string> split (const string &s, const string &delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string item;
vector<string> items;
while ((pos_end = s.find (delimiter, pos_start)) != string::npos) {
item = s.substr (pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
items.push_back (item);
}
items.push_back (s.substr (pos_start));
return items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment