How to draw a string correctly using stringWithFormat

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

I tried the recommended format and did not seem to work so far: [NSString stringWithFormat:@"%10@",@"test"].

I would expect this to return a line with six spaces followed by a β€œtest”, but all I get is a β€œtest” with no spaces.

+5
source share
2 answers

It seems to be stringWithFormatignoring format specifier size queries %@. However, the specifier %sworks correctly:

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

Will print ' test'.

+4
source

C. % nd , n.

.

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);
+3