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

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

One of the benefits of using arg () sprintf () is that the order of the numbered place markers can change if the application strings are translated into other languages, but each arg () will still replace the smallest numbered undefined place marker, regardless where does he appear.

What is the meaning of this? can anyone explain an example?

+5
source share
3 answers

Suppose we start with:

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

Then call:

format.arg("something");

The format will now be:

"something:% 1% 2"

... means you can create a line as you go through it.

Qt, :

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

.

+5
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";

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

+5

What to add to sje397's answer:

When internationalizing your application, you can have this line:

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

Therefore, when calling

formatInAnOtherLanguage.arg("something");

formatInAnOtherLanguage will be

"%3 something %2"

What is the main advantage of the arg function over the sprintf function

+4
source

All Articles