Dmitro
Dmitro

Reputation: 1960

QStringList remove spaces from strings

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.

Upvotes: 5

Views: 6169

Answers (5)

DomTomCat
DomTomCat

Reputation: 8569

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

Upvotes: 2

Darkproduct
Darkproduct

Reputation: 1237

Trimming means to remove spaces in front and at the end of the string. All solutions so far remove only the spaces in front.

Here is the real trimming solution:

str_list.replaceInStrings(QRegExp("^\\s+|\\s+$"), "");

Upvotes: 0

thecharliex
thecharliex

Reputation: 1

QStringList somelist;

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

Upvotes: -1

Olympian
Olympian

Reputation: 768

QRegExp("^\s*")

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

QRegExp("^\\s*")

Upvotes: 8

Christian Goltz
Christian Goltz

Reputation: 746

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

Upvotes: 5

Related Questions