Skip to content

July 18, 2014

Split a String Into Words Using a Vector of Strings and Iterate through it in C++

by noise

Next c++ example shows how to split a string into words by namespaces (or end of line character), store it into a vector of strings and then iterate throug it (mai.cpp).

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
 
using namespace std;
 
int main(int argc, const char * argv[]) {
 
    string str1("the brown fox jumped over the lazy dog");
    vector<string> vector1;
    istringstream iss(str1);
 
    while (iss) {
        string word;
        iss >> word;
        //cout << word << endl;
        vector1.push_back(word);
    }
 
    for (int i; i < vector1.size(); i++) {
        cout << vector1[i] << endl;
    }
 
    return 0;
}
Read more from C and C++ Examples

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments