Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading