Program to extract words from a given String
The 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 the 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.
C++
#include<bits/stdc++.h>
using namespace std;
void printWords(string str)
{
string word;
stringstream iss(str);
while (iss >> word)
cout << word << endl;
}
int main()
{
string s = "sky is blue" ;
printWords(s);
return 0;
}
|
Java
import java.io.*;
class GFG
{
public static void printWords(String s)
{
for (String val: s.split( " " ))
System.out.println(val);
}
public static void main(String args[])
{
String Str = "sky is blue" ;
printWords(Str);
}
}
|
Python3
def printWords(strr):
word = strr.split( " " )
print ( * word, sep = "\n" )
s = "sky is blue"
printWords(s)
|
C#
using System;
class GFG
{
public static void printWords(String s)
{
foreach (String val in s.Split( " " ))
Console.WriteLine(val);
}
static public void Main ()
{
String Str = "sky is blue" ;
printWords(Str);
}
}
|
Javascript
<script>
function printWords(s)
{
s = s.split( " " );
for (let val = 0; val < s.length; val++)
{
document.write(s[val] + "</br>" );
}
}
let Str = "sky is blue" ;
printWords(Str);
</script>
|
Output:
sky
is
blue
Time complexity: O(n) where n is size of input string, since using a while loop
Auxiliary Space: O(1)
Last Updated :
18 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...