Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to right pad a string using stringWithFormat

I would like to be able to right align a string using spaces. I have to be able to use the stringWithFormat: method.

So far I have tried the recommended format and it does not seem to work: [NSString stringWithFormat:@"%10@",@"test"].

I would expect this to return a string that has six spaces followed by "test" but all I am getting is "test" with no spaces.

like image 813
zachzurn Avatar asked Feb 12 '13 00:02

zachzurn


2 Answers

It appears that stringWithFormat ignores the sizing requests of the %@ format specifier. However, %s specifier works correctly:

NSString *test = @"test";
NSString *str = [NSString stringWithFormat:@"%10s", [test cStringUsingEncoding:NSASCIIStringEncoding]];
NSLog(@"'%@'", str);

This prints ' test'.

like image 190
Sergey Kalinichenko Avatar answered Sep 17 '22 20:09

Sergey Kalinichenko


It's C style formatting. %nd means the width is n.

check following code.

NSLog(@"%10@",[NSString stringWithFormat:@"%10@",@"test"]);
NSLog(@"%@",[NSString stringWithFormat:@"      %@",@"test"]);
NSLog(@"%10@", @"test");
NSLog(@"%10s", [@"test" cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSLog(@"%10d", 1);

NSString *str = @"test";
int padding = 10-[str length]; //6
if (padding > 0) 
{
   NSString *pad = [[NSString string] stringByPaddingToLength:padding withString:@" " startingAtIndex:0];
   str = [pad stringByAppendingString:str];
}
NSLog(@"%@", str);
like image 36
bitmapdata.com Avatar answered Sep 17 '22 20:09

bitmapdata.com