Padding string to left

后端 未结 5 1003
渐次进展
渐次进展 2020-12-06 09:12

How can one pad a string to left in objective c. E.g if I have an integer value of 6 I want it to be displayed as 06.

I use stringByPaddingToLength: but

相关标签:
5条回答
  • 2020-12-06 09:35

    for completness (using * placeholder):

    NSString *paddedNumberString = [NSString stringWithFormat:@"%0*d", amountOfZeros, numberNSInteger]
    
    0 讨论(0)
  • 2020-12-06 09:36
    + (NSString *)formatValue:(int)value forDigits:(int)zeros {
        NSString *format = [NSString stringWithFormat:@"%%0%dd", zeros]; 
        return [NSString stringWithFormat:format,value];
    } 
    
    0 讨论(0)
  • 2020-12-06 09:36

    Old thread, I know, but this is a handy way to left pad. I have it my Util class. You can adapt it to right pad if needed. The best part is that it works with whatever padding you want.

    + (NSString *) leftPadString:(NSString *)s withPadding:(NSString *)padding {
        NSString *padded = [padding stringByAppendingString:s];
        return [padded substringFromIndex:[padded length] - [padding length]];
    }
    

    ARC and non-ARC compliant. :)

    To call it, use [Util leftPadString:@"42" withPadding:@"0000"];.

    You could also put it in a category on NSString for an even easier call like [@"42" stringByLeftPadding:@"0000"].

    Both give you 0042.

    0 讨论(0)
  • 2020-12-06 09:39

    This one pads left with 10 zeroes.

    NSString *padded = [NSString stringWithFormat:@"Padded left with zeros: %010d", 65];
    
    0 讨论(0)
  • 2020-12-06 09:44

    Clumsy, but it'll do the job.

    @implementation NSString (LeftPadding)
    
    - (NSString *)stringByPaddingTheLeftToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex
    {
        if ([self length] <= newLength)
            return [[@"" stringByPaddingToLength:newLength - [self length] withString:padString startingAtIndex:padIndex] stringByAppendingString:self];
        else
            return [[self copy] autorelease];
    }
    
    @end
    

    Then you can do:

    NSString *test1 = [@"6" stringByPaddingTheLeftToLength:10 withString:@"0" startingAtIndex:0];
    // test1 = "0000000006"
    
    NSString *test2 = [@"asdf" stringByPaddingTheLeftToLength:10 withString:@"qwer" startingAtIndex:0];
    // test2 = "qwerqwasdf"
    
    NSString *test3 = [@"More than ten characters" stringByPaddingTheLeftToLength:10 withString:@"bamboo" startingAtIndex:0];
    // test3 = "More than ten characters"
    
    NSString *test4 = [test3 stringByPaddingTheLeftToLength:100 withString:test2 startingAtIndex:0];
    // test4 = "qwerqwasdfqwerqwasdfqwerqwasdf...qwerqMore than ten characters"
    
    0 讨论(0)
提交回复
热议问题