Find words which are greater than given length k using stringstream

Given a string containing space-separated words and a number K. The task is to find and print all those words whose length is greater than K using stringstream in C++.

A general solution to solve this problem using loops is discussed in the previous article. In this article, a solution using stringstream in C++ will be discussed.

Examples:



Input : str = "hello geeks for geeks 
          is computer science portal" 
        K = 4
Output : hello geeks geeks computer 
         science portal

Input : str = "string is fun in python"
        K = 3
Output : string python

The idea is to use stringstream to create a stream by splitting the given string into tokens and then process the stream and print the words with length greater than K.

Below is the implementation of the above idea:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find all string 
// which are greater than given length k
// using stringstream
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find all string 
// which are greater than given length k
// using stringstream
void findWords(string str, int K)
{
    string word;
      
    // using stringstream to break
    // the string into tokens
    stringstream ss(str); 
      
    int count = 0;
    while (ss >> word) { // reading words
        if (word.size() > K) {
            cout << word << " ";
            count++;
        }
    }
}
  
// Driver code
int main()
{
    string str = "geeks for geeks";
      
    int k = 4;
  
    findWords(str, k);
      
    return 0;
}

chevron_right


Output:

geeks geeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




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.