QStringList removes spaces from strings

What is the best way to trim all the lines in a list of strings? I am trying to use replaceInStrings:

QStringList somelist; // ... // // add some strings // ... // somelist.replaceInStrings(QRegExp("^\s*"),""); 

but spaces are not removed.

+4
source share
4 answers

As another answer already said, you need to avoid the backslash. You also want to change the expression to match one or more spaces, rather than 0 or more spaces, try using: QRegExp ("^ \\ s +")

+4
source
 QRegExp("^\s*") 

\ is a special character, so you should use \\ when you need to insert a slash in a string

 QRegExp("^\\s*") 
+7
source

If you can use C ++ 11 (qt5 qmake project file: CONFIG += c++11 ), try this short snippet:

 QStringList somelist; // fill list for(auto& str : somelist) str = str.trimmed(); 

It will go through the list with a link, and the result of calling the trimmed function will be returned to the element in the original list.

Without using C ++ 11, you can use Qt methods with Java-Style mutable by iterators:

 QMutableListIterator<QString> it(somelist); while (it.hasNext()) { it.next(); it.value() = it.value().trimmed(); } 

The last method is just perfect if, for example, you want to delete empty lines after they have been trimmed:

 QMutableListIterator<QString> it(somelist); while (it.hasNext()) { it.next(); it.value() = it.value().trimmed(); if (it.value().length() == 0) it.remove(); } 

Remedy really, see Java-style Qt iterator docs

0
source
 QStringList somelist; for(int i = 0; i < somelist.size(); ++i) { QString item = static_cast<QString>(somelist[i]).trimmed() } 
-1
source

All Articles