VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-iterate-through-a-string-word-by-word-in-c/

⇱ How to Iterate through a String word by word in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jun, 2022

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

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: 


Output
GeeksforGeeks
is
a
computer
science
portal
for
Geeks

Another method: This can also be done iteratively

  1. Calculate the length of the given string say n
  2. Iterate on given string from i = 0 to i < n
  3. Check if current character str[i] == " " or i == n - 1
    1. Print the string formed by word and empty the word string
  4. Otherwise, keep appending characters in the word string

Below is the implementation of the 


Output
GeeksforGeeks 
is 
a 
computer 
science 
portal 
for 
Geeks

Time Complexity: O(n), Where n is the size of the given string
Auxiliary Space: O(1)

Comment
Article Tags: