In C++, there is no built-in string split function. A common approach uses istringstream to split by whitespace. For this lesson, a split() helper function has been provided for you:
// split() splits a string into a vector of words by whitespace
string sentence = "hello world foo";
vector<string> words = split(sentence);
// words == {"hello", "world", "foo"}
Here is how the split function works internally:
vector<string> split(const string& s) {
vector<string> result;
istringstream iss(s);
string token;
while (iss >> token) result.push_back(token);
return result;
}
Assignment
Follow the Coding Tutorial and split sentence into a vector of words!
Hint
Use split(sentence) and assign the result to words.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
