How Do I Iterate Over the Words of a String?
Last Updated :
14 Feb, 2024
In C++, strings are character sequences stored in a char array. It may contain text in the form of multiple words representing a sentence. In this article, we will learn how we can iterate over the words of a string in C++.
Example:
Input:
myString ="Geek for Geeks"
Output:
Geek
for
Geeks
Iterate Over the Words of a String in C++
In C++, one of the most simple ways to iterate over the words of a string is using the std::stringstreams. The stringstream creates a stream to the given string. Then we can use cin to iterate word after word as it by default takes the input string till the white space is encountered.
C++ Program to Iterate Over the Words of a String
C++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string S = "Geek for Geeks " ;
stringstream ss(S);
string word;
while (ss >> word) {
cout << word << endl;
}
return 0;
}
|
Time Complexity: O(N) where N is the length of the string.
Space Complexity: O(K) where K is the length of the longest word in the string.
Note: In this program, it is assumed that the words are seperated by a whitespace. If the words are also seperated by a coma or any other character, then we will have to consider it also. Refer to this article for more information.
Share your thoughts in the comments
Please Login to comment...