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
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.