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?
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.
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
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];
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With