如何用空格填充NSString?

时间:2011-12-28 02:18:29

标签: objective-c nsstring padding

例如,我需要NSString至少有8个字符....而不是使用循环来添加左边的填充空格,无论如何都要这样做吗?

Examples:

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

4 个答案:

答案 0 :(得分:17)

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

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;
}

答案 1 :(得分:8)

我只是这样做:

    NSLog(@"%*c%@", 14 - theString.length, ' ', theString);

此外,14是您想要的宽度。

答案 2 :(得分:0)

您可以通过-[NSMutableString appendFormat:]和所有其他NSString“格式化”方法使用C语言printf格式化。它不遵守NSString(在%@上进行格式化),因此您需要将它们转换为ASCII。

String Padding in C

- (NSString *)sample {
    NSArray<NSString *> *input = @[@"Hello", @"Bye", @"Very Long", @"abc"];
    NSMutableString *output = [[NSMutableString alloc] init];
    for (NSString *string in input) {
        [output appendFormat:@"%8s\n", string.UTF8String];
    }
    return output;
}

/*
Return value:
   Hello
     Bye
Very Long
     abc
*/

答案 3 :(得分:-2)

如果你在方法中需要相同的答案,我必须创建一个用于我的项目。原始代码dashblinkenlight

- (NSString *) LeftPadString: (NSString*) originalString LengthAfterPadding: (int)len  paddingCharacter: (char) pad
{
int add = (int) (len - originalString.length);

NSString* paddingCharString = [NSString stringWithFormat:@"%c" , pad];

if (add > 0)
{
    NSString *pad = [[NSString string] stringByPaddingToLength:add withString: paddingCharString startingAtIndex:0];
    return [pad stringByAppendingString:originalString];
}
else
    return originalString;
}