4.2.1.  QStringList and iteration

[ fromfile: iterators.xml id: qstringlist ]

For text processing, it is very useful to work with lists of strings. QStringList is derived from QList<QString> so it inherits all of QList's behavior (Chapter 6). In addition, QStringList has some string-specific convenience functions such as indexOf(), join(), and replaceInStrings().

Converting between lists and individual strings is quite easy with perl-like split() and join() functions. Example 4.1 demonstrates lists, iterations, split() and join().

Example 4.1. src/containers/lists/lists-examples.cpp

#include <QStringList>
#include <QDebug>

/* Some simple examples using QStringList, split and join */

int main() {

    QString winter = "December, January, February";
    QString spring = "March, April, May";
    QString summer = "June, July, August";
    QString fall = "September, October, November";

    QStringList list;
    list << winter;        1
    list += spring;        2
    list.append(summer);   3
    list << fall;

    qDebug() << "The Spring months are: " << list[1] ;
    
    
    QString allmonths = list.join(", "); 
    /* from list to string - join with a ", " delimiter */
    qDebug() << allmonths;

    QStringList list2 = allmonths.split(", ");  
    /* split is the opposite of join. Each month will have its own element. */

    Q_ASSERT(list2.size() == 12); 4

    foreach (QString str, list) {  5
        qDebug() << QString(" [%1] ").arg(str);
    }

    for (QStringList::iterator it = list.begin();
         it != list.end(); ++it) { 6
        QString current = *it;   7
        qDebug() << "[[" << current << "]]";
    }
    
    QListIterator<QString> itr (list2); 8 
    while (itr.hasNext()) {  9
        QString current = itr.next();
        qDebug() << "{" <<  current << "}";
    }
    
    return 0;
}

1

append operator 1

2

append operator 2

3

append member function

4

Q_ASSERTions abort the program if the condition is not satisfied.

5

Qt 4 foreach loop - similar to Perl/Python and Java 1.5 style for loops.

6

C++ STL-style iteration

7

pointer-style dereference

8

Java 1.2 style Iterator

9

Java Iterators point inbetween elements.

The output of this program would look like this:

The Spring months are: March, April, May
December, January, February, March, April, May, June,
 July, August, September, October, November
 [December]
 [January]
 [February]
 [March]
 [April]
 [May]
 [June]
 [July]
 [August]
 [September]
 [October]
 [November]