Iterate over the words in a string in C++

In this tutorial, we will learn how to iterate over the words in a string in C++.

A string is a data type in C++ used to store an array of characters. A string is different from a character array and is terminated with a special character ‘\0’. Strings can include letters, words, spaces, numbers, and even special characters. They are often enclosed in double-quotes. Iteration on strings can be done character by character or we can directly iterate words of the string separated by whitespace using the istringstream class of C++.

Iterating over words using the istringstream class in C++

The istringstream is an input stream class to operate on strings. Since a string containing words is separated by whitespaces we can easily fetch the words of that string using this istringstream class of C++. The words which we will get can now be easily operated on for further use.

Below is an example to illustrate the same.

Syntax:

string s=" Welcome to Codespeedy, hope you are coding well!!"

isstringstream iss(s);
#include <bits/stdc++.h>
#include <string>
#include <sstream>
using namespace std;

int main()
{

  
  string s = "Welcome to Codespeedy, hope you are coding well !!";

    //using istringstream to initialize
    //the given string
  istringstream i_ss(s);

  do {
    string sub;

    i_ss >> sub;//Get word from class istringstream

      //display the word
      //retrieved from istringstream
    cout << sub << endl;

  } while (i_ss);

  return 0;
}

Output:

Welcome

to

Codespeedy,

hope 

you 

are 

coding

well

!!

Code Explanation:

In the above code firstly we are doing the following steps-

  • Declaring the string = “Welcome to Codespeedy, hope you are coding well !!”.
  • Then, we are declaring and initialize the istringstream class using the original string.
  • We are iterating over the string with the help of a do-while loop.
  • Finally, displaying the output of the string which is a word-by-word display of the complete string.

Thus, in this article, we have learned to iterate over the string word by word using the istringstream class of C++.

I hope, you find this article worth a read and informative.

 

Leave a Reply

Your email address will not be published.