Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with "%1" in the argument of QString::arg()?

Everybody loves

QString("Put something here %1 and here %2")     .arg(replacement1)     .arg(replacement2); 

but things get itchy as soon as you have the faintest chance that replacement1 actually contains %1 or even %2 anywhere. Then, the second QString::arg() will replace only the re-introduced %1 or both %2 occurrences. Anyway, you won't get the literal "%1" that you probably intended.

Is there any standard trick to overcome this?

If you need an example to play with, take this

#include <QCoreApplication> #include <QDebug>  int main() {     qDebug() << QString("%1-%2").arg("%1").arg("foo");     return 0; } 

This will output

"foo-%2" 

instead of

"%1-foo" 

as might be expected (not).

    qDebug() << QString("%1-%2").arg("%2").arg("foo"); 

gives

"foo-foo" 

and

    qDebug() << QString("%1-%2").arg("%3").arg("foo"); 

gives

"%3-foo" 
like image 883
Tilman Vogel Avatar asked Mar 09 '11 17:03

Tilman Vogel


People also ask

How do you split a QString?

Solution 1 QStringList myStringList = myString. split(' '). at(1). split(':');

How do you append in QString?

cbegin(), strings. cend(), QString{}); The algorithm does what you'd expect in this example – it starts with an empty QString and adds each of the strings from the vector to it, thus creating a concatenated string.

How do you initialize QString?

Generally speaking: If you want to initialize a QString from a char*, use QStringLiteral . If you want to pass it to a method, check if that method has an overload for QLatin1String - if yes you can use that one, otherwise fall back to QStringLiteral .


2 Answers

See the Qt docs about QString::arg():

QString str; str = "%1 %2"; str.arg("%1f", "Hello"); // returns "%1f Hello" 
like image 71
Johnny Avatar answered Sep 19 '22 11:09

Johnny


Note that the arg() overload for multiple arguments only takes QString. In case not all the arguments are QStrings, you could change the order of the placeholders in the format string:

QString("1%1 2%2 3%3 4%4").arg(int1).arg(string2).arg(string3).arg(int4); 

becomes

QString("1%1 2%3 3%4 4%2").arg(int1).arg(int4).arg(string2, string3); 

That way, everything that is not a string is replaced first, and then all the strings are replaced at the same time.

like image 36
Andreas Haferburg Avatar answered Sep 20 '22 11:09

Andreas Haferburg