如何用空格填充NSString?

问题描述:

例如,我需要NSString至少有8个字符....而不是使用循环在其上添加左填充空格,反正有这样做吗?

For example, I need the NSString have at least 8 chars....instead of using a loop to add the left pad spaces on this, is there anyway to do it?

Examples:

Input:    |Output:
Hello     |   Hello
Bye       |     Bye
Very Long |Very Long
abc       |     abc

以下是如何执行此操作的示例:

Here is an example of how you can do it:

int main (int argc, const char * argv[]) {
    NSString *str = @"Hello";
    int add = 8-[str length];
    if (add > 0) {
        NSString *pad = [[NSString string] stringByPaddingToLength:add withString:@" " startingAtIndex:0];
        str = [pad stringByAppendingString:str];
    }
    NSLog(@"'%@'", str);
    return 0;
}