[ 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;list += spring;
list.append(summer);
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);
foreach (QString str, list) {
qDebug() << QString(" [%1] ").arg(str); } for (QStringList::iterator it = list.begin(); it != list.end(); ++it) {
QString current = *it;
qDebug() << "[[" << current << "]]"; } QListIterator<QString> itr (list2);
while (itr.hasNext()) {
QString current = itr.next(); qDebug() << "{" << current << "}"; } return 0; }
| append operator 1 | |
| append operator 2 | |
| append member function | |
| Q_ASSERTions abort the program if the condition is not satisfied. | |
| Qt 4 foreach loop - similar to Perl/Python and Java 1.5 style for loops. | |
| C++ STL-style iteration | |
| pointer-style dereference | |
| Java 1.2 style Iterator | |
| 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]
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |