Create NSString by repeating another string a given number of times
There is a method called stringByPaddingToLength:withString:startingAtIndex:
:
[@"" stringByPaddingToLength:100 withString: @"abc" startingAtIndex:0]
Note that if you want 3 abc's, than use 9 (3 * [@"abc" length]
) or create category like this:
@interface NSString (Repeat)
- (NSString *)repeatTimes:(NSUInteger)times;
@end
@implementation NSString (Repeat)
- (NSString *)repeatTimes:(NSUInteger)times {
return [@"" stringByPaddingToLength:times * [self length] withString:self startingAtIndex:0];
}
@end
NSString *original = @"abc";
int times = 2;
// Capacity does not limit the length, it's just an initial capacity
NSMutableString *result = [NSMutableString stringWithCapacity:[original length] * times];
int i;
for (i = 0; i < times; i++)
[result appendString:original];
NSLog(@"result: %@", result); // prints "abcabc"