Split a Sentence into words in C++

In this post, we are going to discuss how to split a sentence into words in C++. Splitting a sentence into words is useful when we need to perform operations on some or all words of a sentence.

Some example of these type of problems are:-

  1. Converting first letter of each word into upper case.
  2. Check all the occurrence of a particular word in a sentence. 

Note:- Words Should be separated by space.

Method 1: Split a sentence into words in C++

Traverse through the sentence keep adding characters by taking any other reference string variable, whenever we reach a whitespace ‘ ‘ means we reach to the end of word print that reference string and erase it using string.erase() like that print all the words which are separated by white space.

string.erase()

string.erase() erases all the characters from the string and make it available for reusing again.

Syntax : string_name.erase();

C++ code implementation of splitting a sentence into words

#include<bits/stdc++.h>
using namespace std;

  int main()
  {
      string s;
        getline(cin,s);
        
        string str;
        
        for(auto x:s)
        {
            if(x==' ')
            {
                cout<<str<<endl;
                 str.erase();
            }
            
            else
                  str=str+x;
        }
        
        cout<<str;
  }

INPUT

Codespeedy is a programming tutorial website

OUTPUT

Codespeedy
is
a
programming
tutorial
website

Now, similarly, if we want to print different words separated by ‘,’ we can put x==’,’ in checking condition.

Method 2: C++ program Implementation of printing different words of a sentence separated by ‘,’

#include<bits/stdc++.h>
using namespace std;

  int main()
  {
      string s="Astha,Allu,Nagmla,Wanshi";
        
        string str;
        
        for(auto x:s)
        {
            if(x==',')
            {
                cout<<str<<endl;
                 str.erase();
            }
            
            else
                  str=str+x;
        }
        
        cout<<str;
  }

OUTPUT

Astha

Allu

Nagmla

Wanshi

Thanks For Reading !!

Keep Reading and Stay updated. I will come with more useful CPP programming concepts and discuss in my further blogs.

Leave a Reply

Your email address will not be published. Required fields are marked *