find nth word in sentence c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void splitString(const string &str, vector<string> &output)
{
string::size_type start = 0; // Where to start
string::size_type last = str.find_first_of(" "); // Finds the first space
// npos means that the find_first_of wasn't able to find what it was looking for
// in this case it means it couldn't find another space so we are at the end of the
// words in the string.
while (last != string::npos)
{
// If last is greater then start we have a word ready
if (last > start)
{
output.push_back(str.substr(start, last - start)); // Puts the word into a vector look into how the method substr() works
}
start = ++last; // Reset start to the first character of the next word
last = str.find_first_of(" ", last); // This means find the first space and we start searching at the first character of the next word
}
// This will pickup the last word in the file since it won't be added to the vector inside our loop
output.push_back(str.substr(start));
}
int main()
{
string myString("how are you doing");
vector<string> words;
splitString(myString, words);
for (auto i = 0; i != words.size(); ++i)
cout << words[i] << endl;
}
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks