The most elegant way to iterate the words of a string using C++


There is no one elegant way to iterate the words of a C/C++ string. The most readable way could be termed as the most elegant for some while the most performant for others. I've listed 2 methods that you can use to achieve this. First way is using a stringstream to read words separated by spaces. This is a little limited but does the task fairly well if you provide the proper checks. For example,>

Example Code

 Live Demo

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
   string str("Hello from the dark side");
   string tmp; // A string to store the word on each iteration.
   stringstream str_strm(str);
   vector<string> words; // Create vector to hold our words

   while (str_strm >> tmp) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }
   for(int i = 0; i<words.size(); i++)
      cout << words[i] << endl;
}

Output

Hello
from
the
dark
side

Updated on: 30-Jul-2019

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements