Start learning free

LESSON 63 OF 667 · STRINGS I

String Split in C++

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check