Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use format strings to align NSStrings like numbers can be?

I'm using NSLog() to print some tabular data consisting of an NSString and an associated integer.

Assume I know the length of the longest word.

Is there a way using format strings to get this kind of column alignment:

word:tree        rank:5  
word:frog        rank:3  
word:house       rank:2  
word:peppercorn  rank:2  
word:sword       rank:2  
word:antlion     rank:1  

The reason I'm asking about formatting strings is I'm hoping for a lightweight way to format my ghetto debugging output.

Here is what I tried:

NSString *word = @"tree";
NSUInteger rank = 4;
NSString *str = [NSString stringWithFormat:@"word:%-20@ rank:%u", word, rank];
NSLog(@"%@", str);

Result:

word:tree rank:4

No effect at all.

like image 384
willc2 Avatar asked Nov 04 '09 03:11

willc2


1 Answers

The following seems to work, but requires conversion from your NSString's to C-strings.

NSString *word = @"tree";
NSUInteger rank = 4;
NSString *str = [NSString stringWithFormat:@"word:%-20s rank:%u", [word UTF8String], rank];
NSLog(@"%@", str);

Don't know why the field width is being ignored when trying to use an NSString.

like image 111
Anthony Cramp Avatar answered Nov 08 '22 22:11

Anthony Cramp