QBoard » Artificial Intelligence & ML » AI and ML - Python » How do I iterate over the words of a string?

How do I iterate over the words of a string?

  • 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); do { string subs; iss >> subs; cout << "Substring: " << subs << endl; } while (iss); }
    Is there a more elegant way to do this?
      October 18, 2021 2:23 PM IST
    0
  • 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. To iterate through the words, you would first need to split the string into words , using str.split() , and then iterate through that . Example -
    my_string = "this is a string" for word in my_string.split(): print (word)
    Please note, str.split() , without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).
      October 19, 2021 6:24 PM IST
    0
  • # Python3 code to demonstrate
    # to extract words from string
    # using split()
    	
    # initializing string
    test_string = "GeeksforGeeks is a computer science portal for Geeks"
    	
    # printing original string
    print ("The original string is : " + test_string)
    	
    # using split()
    # to extract words from string
    res = test_string.split()
    	
    # printing result
    print ("\nThe words of string are")
    for i in res:
    	print(i)
    


    Output:

    The original string is : GeeksforGeeks is a computer science portal for Geeks
    
    The words of string are
    GeeksforGeeks
    is
    a
    computer
    science
    portal
    for
    Geeks
      October 22, 2021 2:26 PM IST
    0
  • This is similar to Stack Overflow question How do I tokenize a string in C++?Requires Boost external library

    #include <iostream>
    #include <string>
    #include <boost/tokenizer.hpp>
    
    using namespace std;
    using namespace boost;
    
    int main(int argc, char** argv)
    {
        string text = "token  test\tstring";
    
        char_separator<char> sep(" \t");
        tokenizer<char_separator<char>> tokens(text, sep);
        for (const string& t : tokens)
        {
            cout << t << "." << endl;
        }
    }
      December 18, 2021 11:32 AM IST
    0