views:

2180

answers:

2

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

I use stringByPaddingToLength but it pads it to the right like 60.

Your help is much appreciated. Tony

+14  A: 

This one pads left with 10 zeroes.

NSString *padded = [NSString stringWithFormat:@"Padded left with zeros: %010d", 65];
nevan
+1  A: 

Clumsy, but it'll do the job.

@implementation NSString (LeftPadding)

- (NSString *) stringByPaddingTheLeftToLength:(NSUInteger) newLength withString:(NSString *) padString startingAtIndex:(NSUInteger) padIndex
{
    if ([aString length] <= newLength)
        return [[@"" stringByPaddingToLength:newLength - [aString length] withString:padString startingAtIndex:padIndex] stringByAppendingString:aString];
    else
        return [[aString 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"
dreamlax