Find words which are greater than given length k using stringstream
Last Updated :
27 Mar, 2023
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:
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void findWords(string str, int K)
{
string word;
stringstream ss(str);
int count = 0;
while (ss >> word) {
if (word.size() > K) {
cout << word << " " ;
count++;
}
}
}
int main()
{
string str = "geeks for geeks" ;
int k = 4;
findWords(str, k);
return 0;
}
|
Java
import java.util.*;
class Main
{
static void findWords(String str, int K)
{
StringTokenizer st = new StringTokenizer(str);
int count = 0 ;
while (st.hasMoreTokens()) {
String word = st.nextToken();
if (word.length() > K) {
System.out.print(word + " " );
count++;
}
}
if (count == 0 )
System.out.print(
"No word is greater than length " + K);
}
public static void main(String[] args)
{
String str = "geeks for geeks" ;
int k = 4 ;
findWords(str, k);
}
}
|
Python3
def find_words(string, k):
words = string.split()
count = 0
for word in words:
if len (word) > k:
print (word, end = ' ' )
count + = 1
if count = = 0 :
print (f "No word is greater than length {k}" )
string = "geeks for geeks"
k = 4
find_words(string, k)
|
Javascript
function find_words(string, k) {
let words = string.split( ' ' );
let count = 0;
for (let word of words) {
if (word.length > k) {
console.log(word);
count++;
}
}
if (count === 0) {
console.log(`No word is greater than length ${k}`);
}
}
let string = "geeks for geeks" ;
let k = 4;
find_words(string, k);
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
class HelloWorld {
public static void find_words( string str, int k) {
string [] words = str.Split( ' ' );
int count = 0;
for ( int i = 0; i < words.Length; i++) {
string word = words[i];
if (word.Length > k) {
Console.Write(word + " " );
count = count + 1;
}
}
if (count == 0) {
Console.WriteLine( "No word is greater than length " , k);
}
}
static void Main() {
string str = "geeks for geeks" ;
int k = 4;
find_words(str, k);
}
}
|
Share your thoughts in the comments
Please Login to comment...