Open In App
Related Articles

Split a sentence into words in C++

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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
         portal

Method 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 code
int 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 code
int 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 code
int main()
{
    string str = "Geeks for Geeks";
    removeDupWord(str);
    return 0;
}

                    

Output
Geeks
for
Geeks

Time complexity : O(n) 
Auxiliary Space : O(n)

Method 4 (Using std::getline() Function):

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header.

Implementation

C++

// C++ program to print words in a sentence
// Using std::getline() function
#include <iostream>
#include <sstream>
#include <string>
 
int main()
{
    std::string sentence = "Geeks For Geeks";
    std::string word;
 
    std::istringstream iss(sentence);
    while (std::getline(iss, word, ' ')) {
        std::cout << word << std::endl;
    }
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli

                    

Output
Geeks
For
Geeks

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1).

Method 5 (Using Temporary String):

In C++, one approach is to use a temporary string to hold each word as it is extracted from the sentence. The sentence can be split into words by iterating over each character in the sentence and checking for whitespace characters. When a whitespace character is encountered, the temporary string is considered a word and can be added to a list of words. This process is repeated until all characters in the sentence have been processed.

Implementation

C++

// C++ program to print words in a sentence
// Using Temporary String
 
#include <iostream>
#include <string>
#include <vector>
 
int main() {
    std::string sentence = "Geeks For Geeks";
    std::vector<std::string> words;
 
    // Create a temporary string to hold each word
    std::string tempWord;
 
    // Iterate over each character in the sentence
    for (char c : sentence) {
        // Check if the character is a whitespace character
        if (isspace(c)) {
            // If the temporary string is not empty, add it to the list of words
            if (!tempWord.empty()) {
                words.push_back(tempWord);
                tempWord.clear();
            }
        } else {
            // If the character is not a whitespace character, add it to the temporary string
            tempWord.push_back(c);
        }
    }
 
    // Add the last word to the list of words (if there is one)
    if (!tempWord.empty()) {
        words.push_back(tempWord);
    }
 
    // Print the list of words
    for (std::string word : words) {
        std::cout << word << std::endl;
    }
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli

                    

Output
Geeks
For
Geeks

Time Complexity: O(N), where N is the length of the sentence.
Auxiliary Space: O(N)

Method 6 (Using find(), substr() and erase() Functions):

One approach is to use the find(), substr() and erase() functions to split a sentence into words in C++. 

Steps:

  1. Initialises a string with the sentence and declares two variables for the position and the extracted word.
  2. It then uses a while loop to find the spaces in the sentence and extract the words using the substr() function. 
  3. Lastly, it prints out the last word of the sentence.

Implementation

C++

// C++ program to print words in a sentence
// Using find(), substr() and erase() Functions
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string sentence = "Geeks For Geeks";
    size_t pos = 0;
    string word;
    while ((pos = sentence.find(" ")) != string::npos) {
        word = sentence.substr(0, pos);
        cout << word << endl;
        sentence.erase(0, pos + 1);
    }
    cout << sentence;
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli

                    

Output
Geeks
For
Geeks

Time Complexity: O(N), where N is the length of the sentence.
Auxiliary Space: O(1)



Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads