Jump to content

Repeat a string: Difference between revisions

Add Objective-C example.
No edit summary
(Add Objective-C example.)
Line 434:
</lang>
 
=={{header|Objective-C}}==
Objective-C allows developers to extend existing an existing class by adding additional methods to the class without needing to subclass. These extensions are called categories. Category methods are available to all instances of the class, as well as any instances of its subclasses.
 
This task provides us with an opportunity to visit this aspect of the language feature.
 
We will extend NSString, the de facto Objective-C string class in environments that are either compatible with or descend directly from the OPENSTEP specification, such as GNUstep and Mac OS X, respectively, with a method that accomplishes the described task.
 
<lang c>
@interface NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;
@end
 
@implementation NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times {
// 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 concatentate 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 copy] autorelease];
}
@end
</lang>
 
Now, let's put it to use:
 
<lang c>
// Instantiate an NSString by sending an NSString literal our new
// -repeatByNumberOfTimes: selector.
NSString *aString = [@"ha" repeatStringByNumberOfTimes:5];
 
// Display the NSString.
NSLog(@"%@", [aString description]);
// 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}}==
<lang ocaml>let string_repeat s n =
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.