Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I left pad an NSString to fit it in a fixed width?

I have NSString strings that represent times in HH:MM:SS but the HH and a digit of the MM may be omitted.

I need to align columns of these values like this:

1:01:43
  43:23
   7:00

What's the easiest way to do this?

like image 922
dan Avatar asked Jul 01 '11 13:07

dan


Video Answer


4 Answers

Make use of the stringWithFormat method provided in the NSString class. Something like this:

NSString * dateStr = @"05:30";
NSString * formattedStr = [NSString stringWithFormat:@"%8s", [str UTF8String]];

The 8 in %8s is the number of precision digits (or in this case characters) that you want in your formatted string. Input strings shorter than the specified precision will get left padded with spaces, strings longer than it will get truncated. You can read more about format strings for printf here.

Edit Thanks to @Peter for pointing this out. There are some (minor) differences between the format specifiers in standard C, vs Objective C. Refer to Apples documentation on format string specifiers here.

like image 171
Perception Avatar answered Oct 18 '22 23:10

Perception


padding code Different one but might be helpful

NSString *st = [@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];

abc……

[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];

ab

[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];

abc . . .

notice that the first character in the padding is a space

like image 25
Ashok Kumar Avatar answered Oct 18 '22 23:10

Ashok Kumar


I don't think there is an easy way. You can probably write a category method on NSString to do that.

- (NSString *)stringByPaddingLeftToLength:(NSUInteger)aLength withString:(NSString *)padString {
    NSInteger lengthToPad = aLength - [self length];

    if ( lengthToPad > 0 ) {
        NSString * padding = [@"" stringByPaddingToLength:lengthToPad withString:padString startingAtIndex:0];
        NSString * paddedString = [padding stringByAppendingString:self];

        return paddedString;
    } else {
        return [[self copy] autorelease];
    }
}
like image 2
Deepak Danduprolu Avatar answered Oct 18 '22 23:10

Deepak Danduprolu


If you mean a fixed point width, both NSTextField (Cocoa) and UILabel (Cocoa Touch) let you set the alignment. For NSTextView and custom drawing, you'll need to make an NSParagraphStyle (AppKit only) or CTParagraphStyle with the alignment specified.

like image 1
Peter Hosey Avatar answered Oct 18 '22 23:10

Peter Hosey