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"
Solution 1 QStringList myStringList = myString. split(' '). at(1). split(':');
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.
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 .
See the Qt docs about QString::arg():
QString str; str = "%1 %2"; str.arg("%1f", "Hello"); // returns "%1f Hello"
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.
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