Dissecting strings

There is one more group of useful string functionalities that makes QString different from std::string, that is, cutting strings into smaller parts and building larger strings from smaller pieces.

Very often, a string contains substrings that are glued together by a repeating separator (for example, "1,4,8,15"). While you can extract each field from the record using functions that you already know (for example, indexOf), an easier way exists. QString contains a split() method that takes the separator string as its parameter and returns a list of strings that are represented in Qt by the QStringList class. Then, dissecting the record into separate fields is as easy as calling the following code:

QString record = "1,4,8,15,16,24,42"; ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.