First of all, it includes the following libraries:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>
Here is an easy algorithm, using the function find and substr :
vector<string> split(string str, char pattern) {
int posInit = 0;
int posFound = 0;
string splitted;
vector<string> resultados;
while(posFound >= 0){
posFound = str.find(pattern, posInit);
splitted = str.substr(posInit, posFound - posInit);
posInit = posFound + 1;
resultados.push_back(splitted);
}
return resultados;
}
int main()
{
string str;
char pattern;
vector<string> resultados;
cin >> str;
cin >> pattern;
resultados = split(str, pattern);
for(int i = 0; i < resultados.size(); i++){
cout << resultados[i] << endl;
}
return (0);
}
The logic is as follows:
Declare the variable posInit to store the starting position and get the next substring.
Declare the variable posFound used to find the next character pattern or symbol.
While the position ( posFound ) is valid, the algorithm will look for the position in which the pattern is after the initial position.
The splitted variable will store the temporary value of the substring found to store it in the result vector.
To get that substring , we passed the initial position and the position found - initial position. example: if I found the pattern in position 12 of a string and I have my initial position in position 6, the substring will start in position 6 and concatenate the following 12-6 characters.
Once the substring is obtained, I return the following initial position, the position of the found pattern and add 1, since find returns the position of the pattern and the pattern does not want to include it in my substring.
I add the substring to the results list.
posFound will return -1 because posInit will increase the value until no more patterns are found.
Be sure to send the pattern and the string, if not, validate it as you wish, Regards.