Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QStringList remove spaces from strings

Tags:

c++

string

qt

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.

like image 665
Dmitry Avatar asked Jul 21 '11 14:07

Dmitry


People also ask

How do I remove spaces from QString?

[ 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 .

How do I make QStringList empty?

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.

How do you append a QStringList?

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.


3 Answers

QRegExp("^\s*")

\ is special symbol, so you must use \\ when you need to insert slash into string

QRegExp("^\\s*")
like image 86
Olympian Avatar answered Sep 29 '22 07:09

Olympian


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+")

like image 38
Christian Goltz Avatar answered Sep 29 '22 07:09

Christian Goltz


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

like image 45
DomTomCat Avatar answered Sep 29 '22 08:09

DomTomCat