给一个句子,在其中打印出不同的单词。单词之间用空格隔开。
例子:
Input : str = "Geeks for Geeks"
Output : Geeks
for
Geeks
Explanation : All space separated words
are printed line by line.
Input : str = "a computer science portal"
Output : a
computer
science
portal
方法1(编写我们自己的逻辑)
我们遍历所有字符。如果当前字符为空格,则我们到达单词的结尾,我们将打印当前单词并将其重置为空。否则,我们将当前字符附加到单词。
CPP
// C++ program to print words in a sentence
#include
using namespace std;
void removeDupWord(string str)
{
string word = "";
for (auto x : str)
{
if (x == ' ')
{
cout << word << endl;
word = "";
}
else {
word = word + x;
}
}
cout << word << endl;
}
// Driver code
int main()
{
string str = "Geeks for Geeks";
removeDupWord(str);
return 0;
}
CPP
// C++ program to words in a sentence.
#include
using namespace std;
void removeDupWord(char str[])
{
// Returns first token
char *token = strtok(str, " ");
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
// Driver code
int main()
{
char str[] = "Geeks for Geeks";
removeDupWord(str);
return 0;
}
CPP
// C++ program to print words in a sentence
#include
using namespace std;
void removeDupWord(string str)
{
// Used to split string around spaces.
istringstream ss(str);
string word; // for storing each word
// Traverse through all words
// while loop till we get
// strings to store in string word
while (ss >> word)
{
// print the read word
cout << word << "\n";
}
}
// Driver code
int main()
{
string str = "Geeks for Geeks";
removeDupWord(str);
return 0;
}
输出
Geeks
for
Geeks
方法2(使用strtok ())
CPP
// C++ program to words in a sentence.
#include
using namespace std;
void removeDupWord(char str[])
{
// Returns first token
char *token = strtok(str, " ");
// Keep printing tokens while one of the
// delimiters present in str[].
while (token != NULL)
{
printf("%s\n", token);
token = strtok(NULL, " ");
}
}
// Driver code
int main()
{
char str[] = "Geeks for Geeks";
removeDupWord(str);
return 0;
}
输出
Geeks
for
Geeks
方法3(使用stringstream )
CPP
// C++ program to print words in a sentence
#include
using namespace std;
void removeDupWord(string str)
{
// Used to split string around spaces.
istringstream ss(str);
string word; // for storing each word
// Traverse through all words
// while loop till we get
// strings to store in string word
while (ss >> word)
{
// print the read word
cout << word << "\n";
}
}
// Driver code
int main()
{
string str = "Geeks for Geeks";
removeDupWord(str);
return 0;
}
输出
Geeks
for
Geeks
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。