How about the following?
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s("string to split");
istringstream iss(s);
do
{
string sub;
iss >> sub;
cout << "Substring: " << sub << endl;
} } while (iss);
}
The other way is to use the standard library
Maybe this is a better code to look.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
using namespace std;
string sentence = "string to split";
istringstream iss(sentence);
//To output a word
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
//To save a word to a container
vector<string> words;
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
back_inserter(words));
//To create a vector immediately
vector<string> wordsVector{istream_iterator<string>{iss},
istream_iterator<string>{}};
}
© 2024 OneMinuteCode. All rights reserved.