How do I iterate over the words of a string?

iterate over string
how to iterate through words in a string java
how do i iterate over the words of a string c++
iterate through string c++
iterate through std::string c
c++ iterate over list of strings
iterate through string python
string iteration c

I'm trying to iterate over the words of a string.

The string can be assumed to be composed of words separated by whitespace.

Note that I'm not interested in C string functions or that kind of character manipulation/access. Also, please give precedence to elegance over efficiency in your answer.

The best solution I have right now is:

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

using namespace std;

int main()
    string s = "Somewhere down the road";
    istringstream iss(s);

        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);

Is there a more elegant way to do this?

For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance behind the design of the STL.

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>

int main() {
    using namespace std;
    string sentence = "And I feel fine...";
    istringstream iss(sentence);
         ostream_iterator<string>(cout, "\n"));

Instead of copying the extracted tokens to an output stream, one could insert them into a container, using the same generic copy algorithm.

vector<string> tokens;

... or create the vector directly:

vector<string> tokens{istream_iterator<string>{iss},

Iterate over words of a String in Python, Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = “  Split the string. The common delimiter between words in a string is space. The split returns an array. Each element in the array is a word. Use for loop to iterate over the words present in the array. Example 1: Iterate over words of String. In this example, we will iterate over the words of a string and print them one by one. str = 'Hello! I

I use this to split string by a delimiter. The first puts the results in a pre-constructed vector, the second returns a new vector.

#include <string>
#include <sstream>
#include <vector>
#include <iterator>

template <typename Out>
void split(const std::string &s, char delim, Out result) {
    std::istringstream iss(s);
    std::string item;
    while (std::getline(iss, item, delim)) {
        *result++ = item;

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;

Note that this solution does not skip empty tokens, so the following will find 4 items, one of which is empty:

std::vector<std::string> x = split("one:two::three", ':');

How to Iterate through a String word by word in C++, Given a String comprising of many words separated by space, the task is to iterate over these words of the string in C++. Example: Input: str = {“​GeeksforGeeks is a  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 seperated by spaces.

A possible solution using Boost might be:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));

This approach might be even faster than the stringstream approach. And since this is a generic template function it can be used to split other types of strings (wchar, etc. or UTF-8) using all kinds of delimiters.

See the documentation for details.

Iterating through a string word by word, When you do - for word in string: You are not iterating through the words in the string, you are iterating through the characters in the string. If you simply want to iterate over the characters of a string, you can use the 'split' method chained with a ‘forEach’. let str = "character"; str.split('').forEach(char => console.log(char)); split creates an array of characters fron the given string. forEach will iterate the given array.

#include <vector>
#include <string>
#include <sstream>

int main()
    std::string str("Split me by whitespaces");
    std::string buf;                 // Have a buffer string
    std::stringstream ss(str);       // Insert the string into a stream

    std::vector<std::string> tokens; // Create vector to hold our words

    while (ss >> buf)

    return 0;

How do I iterate over the words of a string?, For what it's worth, here's another way to extract tokens from an input string, relying only on standard library facilities. It's an example of the power and elegance  Iterate over string with index using range() range(len (stringObj) ) function will generate the sequence from 0 to n -1 ( n is size of string) . Now iterate over this sequence and for each index access the character from string using operator [] i.e.

For those with whom it does not sit well to sacrifice all efficiency for code size and see "efficient" as a type of elegance, the following should hit a sweet spot (and I think the template container class is an awesomely elegant addition.):

template < class ContainerT >
void tokenize(const std::string& str, ContainerT& tokens,
              const std::string& delimiters = " ", bool trimEmpty = false)
   std::string::size_type pos, lastPos = 0, length = str.length();

   using value_type = typename ContainerT::value_type;
   using size_type  = typename ContainerT::size_type;

   while(lastPos < length + 1)
      pos = str.find_first_of(delimiters, lastPos);
      if(pos == std::string::npos)
         pos = length;

      if(pos != lastPos || !trimEmpty)
               (size_type)pos-lastPos ));

      lastPos = pos + 1;

I usually choose to use std::vector<std::string> types as my second parameter (ContainerT)... but list<> is way faster than vector<> for when direct access is not needed, and you can even create your own string class and use something like std::list<subString> where subString does not do any copies for incredible speed increases.

It's more than double as fast as the fastest tokenize on this page and almost 5 times faster than some others. Also with the perfect parameter types you can eliminate all string and list copies for additional speed increases.

Additionally it does not do the (extremely inefficient) return of result, but rather it passes the tokens as a reference, thus also allowing you to build up tokens using multiple calls if you so wished.

Lastly it allows you to specify whether to trim empty tokens from the results via a last optional parameter.

All it needs is std::string... the rest are optional. It does not use streams or the boost library, but is flexible enough to be able to accept some of these foreign types naturally.

How to iterate over words of String in Python? – 2 Python Examples, The common delimiter between words in a string is space. The split returns an array. Each element in the array is a word. Use for loop to iterate over the words  In this post, we will discuss various methods to iterate over characters in a String in Java. 1. For loop 2. toCharArray() 3. Iterator 4. Guava 5. chars()..

Processing a String One Word or Character at a Time, Because of Go's built in support for Unicode “runes”, processing a string one character at a time is quite straightforward. Simply iterate over the range of that  How can I iterate through a string in Java? This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. @cletus - you can't access original array - String is immutable so same should be the source array. But in Java you can always modify an array, which would

How to extract each word from a string in Java in the simplest way , Try this method, I find it simple. * Add a blank space to your sentence string. * Iterate over the string using a for loop and extract each character while the  will give you the character at a given position, so you can iterate the first String. will give you the poisition a char in a String, or -1 if it's not there. hence you should be able to look for each character in the first string within the second. +1 for providing the necessary pieces instead of doing his homework.

What is the way to find word occurrences in a string using a loop in , Something like this: [code]word_list=['this', 'yellow', 'flower'] sentence = 'I love yellow buttons' for word in word_list: if word in sentence: print('Found')  In this post, we will see how to iterate over characters of a string in C++. 1. Naive. The idea is iterate over the characters of a std::string using a simple for loop and print each character at current index using [] operator.