PDA

View Full Version : How to format a string to a const width padding with space at the tail



lovelypp
25th July 2008, 08:24
I want to format a string to a const width. if the length of string is less than the const value, then padding it with space char at the tail.
For example, with const = 5,
"a" is formatted to "a "
"ab" is formatted to "ab "
"abc" is formatted to "abc "
"abcd" is formatted to "abcd "
"abcde" is formatted to "abcde"

thanks!

muellerp
25th July 2008, 09:41
This is the same answer as with leading "0" for numbers. But instead of right you do a left.

aamer4yu
25th July 2008, 09:47
Do u want spaces to span the 5-x length ? or a single space if the length is less than 5 ??
If its latter, you can do it as -

if(myString.lengt()<5)
myString.append(" ");


if u want the former way then -

myString.append( QString("").fill(MAX-myString.length());

Hope u get the idea, :)
For numbers, u can use prepend with the same logic :)

jpn
27th July 2008, 16:39
Take a look at QString::arg() parameters fieldWidth and fillChar:


A positive value will produce right-aligned text, whereas a negative value will produce left-aligned text.