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

眉间皱痕 提交于 2019-11-27 13:37:56

问题


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"

回答1:


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

QString str;
str = "%1 %2";
str.arg("%1f", "Hello"); // returns "%1f Hello"



回答2:


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.




回答3:


You should try using

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


来源:https://stackoverflow.com/questions/5249598/how-to-deal-with-1-in-the-argument-of-qstringarg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!