在Objective-C / IOS中填充字符串,如PHP的str_pad()函数?

时间:2013-08-16 14:25:39

标签: php ios objective-c ios6 nsstring

我希望能够在IOS中将字符串填充到左侧,直到某个字符长度。我的字符串是长度不同的id号:

1 
12 
356 
456089

我需要它们看起来像这样:

00000000001 
00000000012 
00000000356 
00000456089

在PHP中我会使用str_pad()函数:

$pad_Length = 11;
$padded_string = str_pad($input_string, $pad_Length, "0", STR_PAD_LEFT);            

如何在iOS / Objective-C中完成?

答案:

NSString *input_string = @"123";
int pad_Length = 11;
NSString *padding = [@"" stringByPaddingToLength: pad_Length - [input_string length] 
                                      withString: @"0" 
                                 startingAtIndex: 0];
NSString *padded_string = [padding stringByAppendingString: input_string];

2 个答案:

答案 0 :(得分:5)

我没有测试过这个,但是

NSString* stringToPad = @"123";
NSString* padding = [@"" stringByPaddingToLength: 11 - [stringToPad length] 
                                      withString: @"0" 
                                 startingAtIndex: 0];
NSString* result = [padding stringByAppendingString: stringToPad];

文档stringByPaddingToLength:withString:startingAtIndex:

答案 1 :(得分:2)

您可以尝试将String传输到Integer 就像这样:

NSArray *strs=[NSArray arrayWithObjects:@"123",@"9234",@"125",@"5123", nil];
    for (NSString *str in strs) {
        NSInteger i=[str integerValue];
        NSString *paddedStr=[NSString stringWithFormat:@"%011d",i];
        NSLog(@"%011d",i);
    }