从给定字符串中提取单词的程序
任务是从给定的字符串中提取单词。单词之间可能有一个或多个空格。
例子:
Input : geeks for geeks
Output : geeks
for
geeks
Input : I love coding.
Output: I
love
coding
我们在下面的帖子中讨论了一个解决方案。
如何在 C/C++、 Python和Java中拆分字符串?
在这篇文章中,讨论了使用 stringstream 的新解决方案。
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.
即使单词之间有多个空格,此解决方案也有效。
C++
// C++ program to extract words from
// a string using stringstream
#include
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;
}
Java
// A Java program for splitting a string
// using split()
import java.io.*;
class GFG
{
// Method splits String into
// all possible tokens
public static void printWords(String s)
{
// Using split function.
for (String val: s.split(" "))
// printing the final value.
System.out.println(val);
}
// Driver Code
public static void main(String args[])
{
// Sample string to check the code
String Str = "sky is blue";
// function calling
printWords(Str);
}
}
// This code is contributed
// by Animesh_Gupta
Python3
# Python3 program to extract words from
# a string
def printWords(strr):
word = strr.split(" ")
print(*word, sep="\n")
# Driver code
s = "sky is blue"
printWords(s)
# This code is contributed by shubhamsingh10
C#
// A C# program for splitting a string
// using split()
using System;
class GFG
{
// Method splits String into
// all possible tokens
public static void printWords(String s)
{
// Using split function.
foreach(String val in s.Split(" "))
// printing the final value.
Console.WriteLine(val);
}
// Driver Code
static public void Main ()
{
// Sample string to check the code
String Str = "sky is blue";
// function calling
printWords(Str);
}
}
// This code is contributed
// by shivanisingh
Javascript
输出:
sky
is
blue