Come posso iterare sulle parole di una stringa?

Sto cercando di iterare le parole di una stringa.

Si può supporre che la stringa sia composta da parole separate da spazi bianchi.

Si noti che non sono interessato alle funzioni di stringa C o a quel tipo di manipolazione/accesso ai caratteri. Inoltre, per favore dai la precedenza all'eleganza sull'efficienza nella tua risposta.

La migliore soluzione che ho al momento è:

#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);
}

C'è un modo più elegante per farlo?

Questo è il mio modo preferito per iterare una stringa. Potete fare quello che volete per ogni parola.

string line = "a line of text to iterate through";
string word;

istringstream iss(line, istringstream::in);

while( iss >> word )     
{
    // Do something on `word` here...
}
Commentari (3)

L'STL non ha già un tale metodo disponibile.

Tuttavia, potete usare la funzione C's [strtok()][1] usando il membro [std::string::c_str()][2], oppure potete scrivere il vostro. Ecco un esempio di codice che ho trovato dopo una rapida ricerca su Google ("STL string split"):

void Tokenize(const string& str,
              vector& tokens,
              const string& delimiters = " ")
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

Preso da:

Se hai domande sull'esempio di codice, lascia un commento e ti spiegherò.

E solo perché non implementa un typedef chiamato iteratore o sovraccarica l'operatore `

Commentari (10)

Usare std::stringstream come hai fatto tu funziona perfettamente bene, e fa esattamente quello che volevi. Se però stai cercando un modo diverso di fare le cose, puoi usare [std::find()][1]/[std::find_first_of()][2] e [std::string::substr()][3].

Ecco un esempio:


#include 
#include 

int main()
{
    std::string s("Somewhere down the road");
    std::string::size_type prev_pos = 0, pos = 0;

    while( (pos = s.find(' ', pos)) != std::string::npos )
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        std::cout 
Commentari (1)