How to Iterate Over the Words of a String in C++

by | C++, Programming, Tips

This tutorial will go through how to iterate over the words of a string consisting of multiple words.


Iterate Over Words using istringstream

The simplest way to iterate over words is to use the istringstream class. If the words in a string are separated by whitespace, we can fetch each word from the istringstream object as follows:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
    string str = "C++ is really fun to learn!";
    istringstream iss(str);
    do {
        string word;

        iss >> word;

        cout << word << endl;

    } while (iss);

    return 0;
}

You can test your code by visiting our free C++ code compiler.

Let’s run the code to get the result:

C++
is
really
fun
to
learn!

Iterate Over Words using for-loop

We can iterate over the words in a string using iteratively. The steps of this approach are as follows:

#include <iostream>
#include <string>

// Split provided string to words and print to console
void splitWord(std::string str)
{


    // Create an empty string
    std::string word;

    // Iterate over the string character by character with for loop
    for (int i = 0; i < str.length(); i++) {

        // Check if character at current iteration is equal to ' ' or
        // is the last character
        if (str[i] == ' ' or i == (str.length() - 1)) {

            // If whitespace or the last character print the string including current character
            std::cout << word + str[i] << std::endl;
            word = "";
        }
            // Add current character to string

        else {
            word += str[i];
        }
    }
}

int main()
{
    // Given string
    std::string str = "C++ is really fun to learn!";

    splitWord(str);

    return 0;
}

Let’s run the code to see the result:

C++ 
is 
really 
fun 
to 
learn!

Iterate Over Words using strtok

Using the provided separators, we can also use the strtok method to split a string into words. Let’s look at an example using strtok:

#include <cstdio>
#include <cstring>

int main ()
{

    // Define a character array
    char str[] ="C++ is really fun to learn!";

    // Character pointer
    char * pch;

    printf ("Splitting string \"%s\" into tokens:\n",str);

    // Return pointers to the first token
    pch = strtok (str," ,.-");

    // Check for delimiter
    while (pch != nullptr)

    {
    // Use strtok to go through other tokens
        printf ("%s\n",pch);
        pch = strtok (nullptr, " ,.-");
    }
    return 0;
}
C++
is
really
fun
to
learn!

Iterate Over Words using Boost Library

We can also use the boost::split method from the Boost library. The split method functions similarly to strtok, where an input sequence is split into tokens given a specific separator. Let’s look at how to implement the split method with an example,

#include <iostream>
#include <string>
#include <boost/algorithm/string.hpp>


int main() {

    // Define an input string

    std::string input=  "C++ is really fun to learn!";

    // Define a container to hold copies of references to the substrings

    std::vector<std::string> result;

    // Split based on tab or white space
    boost::split(result, input, boost::is_any_of("\t "));

    // Iterate over vector using for loop

    int n = result.size();

    for (int i = 0; i<n; i++)

    // Print words to console

        std::cout << result[i] << std::endl;

    return 0;

}

Let’s run the code to see the result:

C++
is
really
fun
to
learn!

Summary

Congratulations on reading to the end of this tutorial!

For further reading on C++, go to the articles:

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨