How to Iterate through a String word by word in C++
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:
// 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; } |
GeeksforGeeks is a computer science portal for Geeks
Recommended Posts:
- C++ program to read file word by word
- Find the first repeated word in a string
- Program to print the Alphabets of a Given Word using * pattern
- Tokenizing a string in C++
- Prime String
- string find in C++
- std::string class in C++
- std::string::compare() in C++
- Raw string literal in C++
- getline (string) in C++
- std::string::data() in C++
- std::string::assign() in C++
- std::string::push_back() in C++
- C++ String Class and its Applications | Set 2
- Concatenate suffixes of a String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



