find nth word in sentence c 2b 2b

Solutions on MaxInterview for find nth word in sentence c 2b 2b by the best coders in the world

showing results for - "find nth word in sentence c 2b 2b"
Veronica
27 Jun 2018
1#include <iostream>
2#include <string>
3#include <vector>
4
5using namespace std;
6
7void splitString(const string &str, vector<string> &output)
8{
9    string::size_type start = 0; // Where to start
10    string::size_type last = str.find_first_of(" "); // Finds the first space
11
12    // npos means that the find_first_of wasn't able to find what it was looking for
13    // in this case it means it couldn't find another space so we are at the end of the
14    // words in the string.
15    while (last != string::npos)
16    {
17        // If last is greater then start we have a word ready
18        if (last > start)
19        {
20            output.push_back(str.substr(start, last - start)); // Puts the word into a vector look into how the method substr() works
21        }
22
23        start = ++last; // Reset start to the first character of the next word
24        last = str.find_first_of(" ", last); // This means find the first space and we start searching at the first character of the next word
25    }
26
27    // This will pickup the last word in the file since it won't be added to the vector inside our loop
28    output.push_back(str.substr(start));
29}
30
31int main()
32{
33    string myString("how are you doing");
34    vector<string> words;
35    splitString(myString, words);
36
37    for (auto i = 0; i != words.size(); ++i)
38        cout << words[i] << endl;
39}
similar questions
queries leading to this page
find nth word in sentence c 2b 2b