9

I want to use .arg() on 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 isn't the actual output since %11 is interpreted as placeholder #11 instead of place holder #1 followed by a literal 1.

Is there a better solution than the following?

qDebug() << QString("%1%2%3").arg(66).arg(1).arg(77);
Silicomancer
  • 8,604
  • 10
  • 63
  • 130

3 Answers3

3

The arg replaces sequence with lowest value after %. Range must be betwen 1 and 99. So you dont have to use 1 index you can use two digit number instead one digit number.

Try this and see what will happen:

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

This should give you expected result (I've test it on qt 5.4 and it works perfectly).

I've also tested solution form comment under the question and it works to:

qDebug() << QString("%011%02").arg(66).arg(77);
Marek R
  • 32,568
  • 6
  • 55
  • 140
1

The sense of arg() is that it is replacing everything from %1 to %99 that is why you should not have %11. There are several ways to escape this.

Your way is fine as well as you can have 1 as constant earlier in your code:

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

Or you can have:

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

Using QString::number is ok too as was specified in comment.

demonplus
  • 5,613
  • 12
  • 49
  • 68
1

Try one of the following approaches:

  • QString::number(66) + "1" + QString::number(77)
  • QString("%1 1 %2").arg(66).arg(77).replace(" ", "")
Murphy
  • 3,827
  • 4
  • 21
  • 35
  • I will need advanced number formatting (which isn't available using QString::number). Still this surely is an alternative for standard cases. – Silicomancer Feb 20 '16 at 10:09
  • Marek's solution is surely the universal one ***poke to brainprom***. – Murphy Feb 20 '16 at 20:45