venkat
venkat

Reputation: 131

NSString Manipulation

I would like to manipulate the NSString like as

(0) Likes (1). (see. (2))

(0) = Raman

(1) = You

(2) = ThisGift

to

Raman Likes You. (see. ThisGift)

I dont know what approch can solve this problem.

Thanks in Advance, Regards

Venkat.

Upvotes: 0

Views: 745

Answers (3)

outis
outis

Reputation: 77400

If you're allowed to change the template format, you can use format strings.

NSString *template1 = @"%1$@ Likes %2$@. (see. %3$@)",
         *template2 = @"%2$@ got a %3$@ from %1$@.";
NSString *msg1 = [NSString stringWithFormat:template1,@"Raman",@"You",@"ThisGift"],
         *msg2 = [NSString stringWithFormat:template2,@"Raman",@"You",@"ThisGift"];

or (if the format string can always depend on the arguments being in replacement order):

NSString *template = @"%@ Likes %@. (see. %@)";
NSString *msg = [NSString stringWithFormat:template,@"Raman",@"You",@"ThisGift"];

Upvotes: 2

DarkDust
DarkDust

Reputation: 92316

See -[NSString stringByReplacingOccurrencesOfString:withString:]

NSString *foo = @"(0) likes (1). (see (2))";
NSString *bar;
bar = [foo stringByReplacingOccurrencesOfString:@"(0)"
                                     withString:@"Raman"];
bar = [bar stringByReplacingOccurrencesOfString:@"(1)"
                                     withString:@"You"];
bar = [bar stringByReplacingOccurrencesOfString:@"(2)"
                                     withString:@"ThisGift"];

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243146

-[NSString stringByReplacingOccurrencesOfString:withString:].

You use it like this:

NSString * source = @"(0) Likes (1). (see. (2))";
source = [source stringByReplacingOccurrencesOfString:@"(0)" withString:@"Raman"];
NSLog(@"%@", source);  //logs "Raman Likes (1). (see. (2))"

Upvotes: 5

Related Questions