The following code uses a regex to find the "|" and split the surrounding elements into an array. It then prints each of those elements, using cout
, in a for
loop.
This method allows for splitting with regex as an alternative.
#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
using namespace std;
vector<string> splitter(string in_pattern, string& content){
vector<string> split_content;
regex pattern(in_pattern);
copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
sregex_token_iterator(),back_inserter(split_content));
return split_content;
}
int main()
{
string sentence = "This|is|the|sentence";
//vector<string> words = splitter(R"(\s+)", sentence); // seperate by space
vector<string> words = splitter(R"(\|)", sentence);
for (string word: words){cout << word << endl;}
}