Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Iterate through a String word by word in C++

  • Last Updated : 18 Oct, 2019

Given a String comprising of many words separated by space, the task is to iterate over these words of the string in C++.

Example:

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

Input: str = {“GeeksforGeeks is a computer science portal for Geeks”};
Output:
GeeksforGeeks
is
a
computer
science
portal
for
Geeks

Input: str = {“Geeks for Geeks”};
Output:
Geeks
for
Geeks



Approach: istringstream class is best suitable for this purpose. When a string is given split by whitespace, this class can be used to easily fetch and use each word of the String.

Syntax:

string str = {"Geeks for Geeks"};
istringstream iss(str);

Below is the implementation of the above approach:




// C++ program to Iterate through
// a String word by word
  
#include <iostream>
#include <sstream>
#include <string>
  
using namespace std;
  
// Driver code
int main()
{
  
    // Get the String
    string str = "GeeksforGeeks is a computer "
                 "science portal for Geeks";
  
    // Initialise the istringstream
    // with the given string
    istringstream iss(str);
  
    // Iterate the istringstream
    // using do-while loop
    do {
        string subs;
  
        // Get the word from the istringstream
        iss >> subs;
  
        // Print the word fetched
        // from the istringstream
        cout << subs << endl;
  
    } while (iss);
  
    return 0;
}
Output:
GeeksforGeeks
is
a
computer
science
portal
for
Geeks



My Personal Notes arrow_drop_up