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

旧城冷巷雨未停 提交于 2019-12-05 00:00:29

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.

Yes, just like printf.

According to the documentation, stringWithFormat: obeys the IEEE printf specification, which allows all kinds of modifications on the individual arguments. The documentation has a restricted subset of that information, but they link to the OpenGroup printf specification for Unix to give the full information (worth a read, you can accomplish a lot of tricks with format specifiers).

Try this, to get exactly what you've pasted above:

NSString *word = @"butterfly";
NSUInteger rank = 4;
NSString *str = [NSString stringWithFormat:@"word:%-11s rank:%u", [word UTF8String], rank];

Here's an example of how I format my debugging output (I don't use NSLog, I wrap printing to standard error to get file and line, too):

fprintf(stderr, "%s | %30s:%-5d | %s", [[[NSDate date] description] UTF8String],
    [fileName UTF8String], line, [body UTF8String]);

If you do something like the earlier answer:

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

... you can get encoding-conversion problems for non-ASCII characters... stringWithFormat seems to assume the system default encoding, which is still MacRoman for some crazy reason. You can drop down to the stdlib level -- do all your formatting with sprintf into your own buffer, and then you can control the encoding when creating an NSString from that -- but that's cumbersome. If anyone knows a convenient workaround, I'm all ears.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!