[NSString stringByPaddingToLength withString startingAtIndex]
Returns a new string formed from the receiver by either removing characters from the end, or by appending as many occurrences as necessary of a given pad string.
- (NSString *)stringByPaddingToLength:(NSUInteger)newLength withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex
Parameters
- newLength
- The new length for the receiver.
- padString
- The string with which to extend the receiver.
- padIndex
- The index in padString from which to start padding.
Return Value of [NSString stringByPaddingToLength withString startingAtIndex]
A new string formed from the receiver by either removing characters from the end, or by appending as many occurrences of padString as necessary.
Discussion of [NSString stringByPaddingToLength withString startingAtIndex]
Here are some examples of usage:
[@"abc" stringByPaddingToLength: 9 withString: @"." startingAtIndex:0];
|
// Results in "abc......"
|
[@"abc" stringByPaddingToLength: 2 withString: @"." startingAtIndex:0];
|
// Results in "ab"
|
[@"abc" stringByPaddingToLength: 9 withString: @". " startingAtIndex:1];
|
// Results in "abc . . ."
|
// Notice that the first character in the padding is " "
|
Example of [NSString stringByPaddingToLength withString startingAtIndex]
int main (int argc, const char * argv[]) {
NSString *str = @"Hello";
int add = 8-[str length];
if (add > 0) {
NSString *pad = [[NSString string] stringByPaddingToLength:add withString:@" " startingAtIndex:0];
str = [pad stringByAppendingString:str];
}
NSLog(@"'%@'", str);
return 0;
}
Example of [NSString stringByPaddingToLength withString startingAtIndex]
- (NSString *)formattedStringWithStrings:(NSArray *)strings {
NSString *str1 = [[strings objectAtIndex:0] stringByPaddingToLength:3 withString:@" " startingAtIndex:0];
NSString *str2 = [[strings objectAtIndex:1] stringByPaddingToLength:20 withString:@" " startingAtIndex:0];
NSString *str3 = [[strings objectAtIndex:2] stringByPaddingToLength:3 withString:@" " startingAtIndex:0];
NSString *str4 = [[strings objectAtIndex:3] stringByPaddingToLength:10 withString:@" " startingAtIndex:0];
NSString *str5 = [[strings objectAtIndex:4] stringByPaddingToLength:15 withString:@" " startingAtIndex:0];
return [NSString stringWithFormat:@"%@%@%@%@%@", str1, str2, str3, str4, str5];
}
Example of [NSString stringByPaddingToLength withString startingAtIndex]
@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