Home > Mobile >  Splitting QString on spaces and keeping the space in QList - best or 'canonical' way
Splitting QString on spaces and keeping the space in QList - best or 'canonical' way

Time:02-13

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:

"This" "is" "an" "exemplary" "text"

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

"This_" "is_" "an_" "exemplary_" "text"

Any suggestion would be welcomed.

CodePudding user response:

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

  • Related