Split a sentence into words in C++
Give a sentence, print different words present in it. Words are separated by space.
Examples:
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
portalMethod 1 (Writing our own logic):
We traverse through all characters. If current character is space, we have reached end of a word, we print current word and reset it to empty. Else we append current character to word.
Implementation:
CPP
// C++ program to print words in a sentence#include <bits/stdc++.h>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 codeint main(){ string str = "Geeks for Geeks"; removeDupWord(str); return 0;} |
Output
Geeks for Geeks
Complexity Analysis:
- Time complexity : O(n)
- Auxiliary Space : O(n)
Method 2 (Using strtok()):
Implementation:
CPP
// C++ program to words in a sentence.#include <bits/stdc++.h>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 codeint main(){ char str[] = "Geeks for Geeks"; removeDupWord(str); return 0;} |
Output
Geeks for Geeks
Note: strtok() function cannot be used with C++ STL string. It requires string to be character array.
Complexity Analysis:
- Time complexity : O(n)
- Auxiliary Space : O(n)
Method 3 (Using stringstream):
Implementation:
CPP
// C++ program to print words in a sentence#include <bits/stdc++.h>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 codeint main(){ string str = "Geeks for Geeks"; removeDupWord(str); return 0;} |
Output
Geeks for Geeks
Time complexity : O(n)
Auxiliary Space : O(n)





Please Login to comment...