Question

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.

Was it helpful?

Solution

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'.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top