QString :: arg () with the number after the placeholder

I want to use .arg () for a string. This is an example:

qDebug() << QString("%11%2").arg(66).arg(77); 

I would like to get the output 66177 , but, of course, this is not the actual output, since %11 interpreted as placeholder # 11 instead of the owner of place # 1, followed by the letter 1.

Is there a better solution than the following?

 qDebug() << QString("%1%2%3").arg(66).arg(1).arg(77); 
+5
source share
3 answers

arg replaces the sequence with the lowest value after % . The range should be between 1 and 99. Therefore, you do not need to use index 1 , you can use a two-digit number instead of a single character.

Try this and see what happens:

 qDebug() << QString("%111%22").arg(66).arg(77); 

This should give the expected result (I tested it on qt 5.4 and it works great).

I also tested the comment on the form form in the question, and it works with:

 qDebug() << QString("%011%02").arg(66).arg(77); 
+1
source

The meaning of arg() is that it replaces everything from %1 to %99 , so you should not have %11 . There are several ways to avoid this.

Your path is fine, as you may have 1 as a constant before in your code:

 qDebug() << QString("%1%2%3").arg(66).arg(1).arg(77); 

Or you can:

 qDebug() << QString("%1").arg(66) + "1" + QString("%1").arg(77); 

Using QString::number is fine too, as indicated in the comment.

+1
source

Try one of the following methods:

  • QString::number(66) + "1" + QString::number(77)
  • QString("%1 1 %2").arg(66).arg(77).replace(" ", "")
+1
source

Source: https://habr.com/ru/post/1243438/


All Articles