What a best way for trimming all strings in string list? I try to use replaceInStrings:
QStringList somelist;
// ... //
// add some strings
// ... //
somelist.replaceInStrings(QRegExp("^\s*"),"");
but spaces not removed.
[ QString::simplified ] Returns a string that has whitespace removed from the start and the end, and that has each sequence of internal whitespace replaced with a single space. Option 2: Use a QRegExp to capture all types of white space in remove .
Empty string QString("") and null string QString() both return true when compared to an empty string. Then the test of QList::removeAll(const T &value) will remove both empty and null strings from the list.
Strings can be added to a list using append(), operator+=() or operator<<(), e.g. QStringList fonts; fonts. append( "Times" ); fonts += "Courier"; fonts += "Courier New"; fonts << "Helvetica [Cronyx]" << "Helvetica [Adobe]"; String lists have an iterator, QStringList::Iterator(), e.g.
QRegExp("^\s*")
\ is special symbol, so you must use \\
when you need to insert slash into string
QRegExp("^\\s*")
As another answer already told, you need to escape the backslash. You also want to change the expression to match one or more spaces and not 0 or more spaces, try using: QRegExp("^\\s+")
If you can use C++11 (qt5 qmake project file: CONFIG += c++11
), then try this short snippet:
QStringList somelist;
// fill list
for(auto& str : somelist)
str = str.trimmed();
It will run through the list with a reference and the trimmed
function call result will be assigned back to the item in the original list.
Without the use of C++11 you can use Qt
methods with Java-Style, mutable iterators:
QMutableListIterator<QString> it(somelist);
while (it.hasNext()) {
it.next();
it.value() = it.value().trimmed();
}
The latter method is just perfect, if you, for instance, want to remove empty strings 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();
}
The remove is valid, see the Qt java-style iterator docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With