How Do I Iterate Over the Words of a String?
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 Beginner" Output: Geek for Beginner
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++
// C++ program to Iterate Over the Words of a String #include <iostream> #include <sstream> #include <string> using namespace std; int main() { // declare a string of words string S = "Geek for Beginner " ; // Initialzie the string stream stringstream ss(S); string word; // access each word of the string in the form of tokens // and print it while (ss >> word) { cout << word << endl; } return 0; } |
Geek for Beginner
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.
Contact Us