Repeat a string: Difference between revisions
Content added Content deleted
m (→Icon and Unicon: header simplification) |
|||
Line 438: | Line 438: | ||
@implementation NSString (RosettaCodeAddition) |
@implementation NSString (RosettaCodeAddition) |
||
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times { |
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times { |
||
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0]; |
|||
// This assertion ensures that we're repeating the string at least once. |
|||
NSAssert (times >= 0, |
|||
@"The receiver should be repeated at least once."); |
|||
// We need a mutable copy of ourself to concatenate the repetitions. |
|||
NSMutableString *workingCopy = [self mutableCopy]; |
|||
// Append the receiver to workingCopy the number of times specified. |
|||
for (NSUInteger i = 1; i <= times; i++) |
|||
[workingCopy appendString:self]; |
|||
// All done; return an autoreleased copy. |
|||
return [workingCopy autorelease]; |
|||
} |
} |
||
@end</lang> |
@end</lang> |
||
Line 460: | Line 448: | ||
// Display the NSString. |
// Display the NSString. |
||
NSLog(@"%@", |
NSLog(@"%@", aString);</lang> |
||
// NB: The other Rosetta Code implementations interpret the task in a |
|||
// mathematical sense, i.e. repeating "ha" five times being analogous |
|||
// to multiplying the string five times. This implementation does not |
|||
// follow that convention for one reason: repeating a string _once_ |
|||
// should yield two strings, the original string appended to a single |
|||
// repetition of the string. In other words, repeating @"ha" once should |
|||
// return @"haha", otherwise the method isn't upholding the contract |
|||
// implied by its name.</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |