开发者

what is the difference between QString::sprintf and QString::arg in Qt?

开发者 https://www.devze.com 2023-01-27 23:37 出处:网络
QString documentation in http://doc.qt.io/qt-5/qstring.html#arg says One advantage of using arg() over

QString documentation in http://doc.qt.io/qt-5/qstring.html#arg says

One advantage of using arg() over sprintf() is that the order of the numbered place markers can change, if the application's strings are translated into other languages, but each arg() will still replace the lowest numbered unreplaced place marker, no matter where it appears.

what 开发者_JS百科is the meaning of this? can anyone please explain with example?


int day = 1;
int month = 12;
int year = 2010;
QString dateString = QString(tr("date is %1/%2/%3")).arg(month).arg(day).arg(year);
// dateString == "date is 12/1/2010";

With German translation "Das Datum ist: %2.%1.%3": dateString = "Das Datum ist: 1.12.2010"


Say we start with:

QString format("%1: %2 %3);

Then call:

format.arg("something");

Format will now be:

"something: %1 %2"

...meaning you can build up the string as you go.

Changing the order of the place markers is possible through Qt's translation mechanism, which allows you to say:

format = tr("Hi, %1, I hope you are %2");

and add it to your translation table and have the parameters in a different order for different languages.


A thing to add to sje397 answer:

When internationalizing your application you can have a string like that:

QString formatInAnOtherLanguage("%3 %1 %2");

So when calling

formatInAnOtherLanguage.arg("something");

formatInAnOtherLanguage will be

"%3 something %2"

That's the main advantage of the arg function over the sprintf function

0

精彩评论

暂无评论...
验证码 换一张
取 消