Program to extract words from a given String

Task is to extract words from a given string. There may be one or more space between words.

Examples:

Input : geeks for geeks
Output : geeks
         for
         geeks

Input : I love   coding.
Output : I 
         love
         coding



We have discussed a solution in below post.
How to split a string in C/C++, Python and Java?

In this post, a new solution using stringstream is discussed.

1. Make a string stream.
2. extract words from it till there are still words in the stream.
3. Print each word on new line.

This solution works even if we have multiple spaces between words.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to extract words from
// a strung using stringstream
#include<bits/stdc++.h>
using namespace std;
  
void printWords(string str)
{
    // word variable to store word
    string word;
  
    // making a string stream
    stringstream iss(str);
  
    // Read and print each word.
    while (iss >> word)
        cout << word << endl;
}
  
// Driver code
int main()
{
    string s = "sky is blue";
    printWords(s);
    return 0;
}

chevron_right


Output:

sky
is
blue

This article is contributed by Tanya Anand. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.