Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt

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 is the meaning of this? can anyone please explain with example?

like image 671
SunnyShah Avatar asked Dec 01 '10 09:12

SunnyShah


2 Answers

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"

like image 129
hmuelner Avatar answered Oct 26 '22 06:10

hmuelner


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.

like image 44
sje397 Avatar answered Oct 26 '22 05:10

sje397