views:

60

answers:

3

Hello everyone. I want to do something like:

string s1 set to null
s2: "abc"

repeat 10 times

s1=s1+s2

How can I do this in objective-c?

A: 

I am not sure but make a loop

for(i=0;i<10;i++)
{
   s1=s1+s2;
}
Dorababu
+3  A: 

Is this suitable?:

NSMutableString *s1 = [[NSMutableString alloc] initWithString:@""];
NSString *s2 = @"abc";

for(NSInteger idx = 0; idx < 10; ++idx) {
   [s1 appendString:s2];
}

...

[s1 release];
thatsdisgusting
+1. But in spirit of obj-c memory management rules and the bugs we see here so often, maybe better call `[NSMutableString stringWithString:@""]` to get an autoreleased string.
mvds
Or just `[NSMutableString string]`.
Wevah
A: 

Although @thatsdisgusting gave a perfect answer, here's a shortcut:

NSMutableString *a = [NSMutableString stringWithCapacity:0];
NSString *pad = @"abc";
NSString *ret = [a stringByPaddingToLength:10*[pad length] withString:pad
                                                           startingAtIndex:0];

abusing stringByPaddingToLength.

mvds