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"
24
задан Tilman Vogel 9 March 2011 в 17:24
поделиться