The following trick using istringstream
to split a string with white spaces.
int main() {
string sentence(\"Cpp is fun\");
istringstream
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::istringstream iss { "Cpp|is|fun" };
std::string s;
while ( std::getline( iss, s, '|' ) )
std::cout << s << std::endl;
return 0;
}
Demo
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;}
}
Generally speaking the istringstream approach is slow/inefficient and requires at least as much memory as the string itself (what happens when you have a very large string?). The C++ String Toolkit Library (StrTk) has the following solution to your problem:
#include <string>
#include <vector>
#include <deque>
#include "strtk.hpp"
int main()
{
std::string sentence1( "Cpp is fun" );
std::vector<std::string> vec;
strtk::parse(sentence1," ",vec);
std::string sentence2( "Cpp,is|fun" );
std::deque<std::string> deq;
strtk::parse(sentence2,"|,",deq);
return 0;
}
More examples can be found Here