[SOLVED] Splitting QString on spaces and keeping the space in QList – best or 'canonical' way


As in the title, I would like to ask what is the best way to split a QString on spaces and – where relevant – keep the spaces as parts of the resulting QList elements. I’m interested in the most efficient method of doing this, considering modern C++ and Qt >= 6.0 paradigms.

For the purpose of this question I will replace normal spaces with ‘_’ – I hope it makes the problem easier to understand.

Imagine the following code:

QString myString = "This_is_an_exemplary_text";
for (auto word : myString.split('_')) {
   qDebug() << word;

The output of the code would be:


Information about the spaces was lost in the splitting process. Is there a smart way to preserve it, and have the following output:


Any suggestion would be welcomed.


Consider myString.split(QRegularExpression("(?<= )") The regular expression says "an empty substring preceded by a space", using the positive look-behind syntax.

Answered By – Igor Tandetnik

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *