5

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?

Christophe Weis
  • 2,518
  • 4
  • 28
  • 32
SunnyShah
  • 28,934
  • 30
  • 90
  • 137
  • 1
    Another advantage of arg(): sprintf() is [deprecated](http://qt-project.org/doc/qt-4.8/qstring.html#sprintf). – jlstrecker Aug 20 '12 at 20:32

3 Answers3

6
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"

hmuelner
  • 8,093
  • 1
  • 28
  • 39
5

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.

sje397
  • 41,293
  • 8
  • 87
  • 103
4

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

Patrice Bernassola
  • 14,136
  • 6
  • 46
  • 59