suse
suse

Reputation: 10563

append in middle of NSString in iPhone programming

how to append the value of string in between NSString?

for example:

NSString* str1 = @"Hello";

NSString* str2 = @"Hi.."/*add contents of str1*/@"how r u??";

please tell me how to achieve this??

Upvotes: 3

Views: 4064

Answers (2)

Johan Kool
Johan Kool

Reputation: 15927

There are multiple answers possible. It depends a bit on how you want to figure out where to insert the text. One possibility is:

NSString *outStr = [NSString stringWithFormat:"%@%@%@", [str2 substringToIndex:?], str1, [str2 substringFromIndex:?]];

Upvotes: 7

kennytm
kennytm

Reputation: 523724

(Append always means add to the end. That's inserting a string in the middle.)

If you simply want to construct a literal string, use

#define STR1 @"Hello"
NSString* str2 = @"Hi..." STR1 @" how r u??";

To insert it in run time you need to convert str2 into a mutable string and call -insertString:atIndex:.

NSMutableString* mstr2 = [str2 mutableCopy];
[mstr2 insertString:str1 atIndex:4];
return [mstr2 autorelease];

Upvotes: 4

Related Questions