Created
September 6, 2021 16:47
-
-
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
This file contains 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 <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