KikX
KikX

Reputation: 217

Include a variable in the middle of NSString

I currently tried to use this:

NSString *hello = @"Hello";
NSString *whatever = [hello stringByAppendingString:@", world!"];

it's possible to use this but it will make a lot of work because my goal is to do something like this:

NSString = "Hello" +variable+ "My name is" +variable + ",Good day"

Upvotes: 0

Views: 75

Answers (3)

Bera Bhavin
Bera Bhavin

Reputation: 703

You can use the NSString method stringWithFormat.

Objective C

NSString *strConcat = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",var1,var2];

Swift

let strConcat = "Hello "+ strOne + " My Name is " + strTwo

OR

let strConcateSecond = "Hello \(strOne) My Name is \(strTwo)"

Upvotes: 0

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16446

You can use NSString's method stringWithFormat

example

NSString *str = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",var1,var2]

or

NSString *str = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",@"Stack Overflow",@"FreelancsAndroidLovesyou"]

Upvotes: 2

PPL
PPL

Reputation: 6555

You can do this alternatively, if both values are same then you can do this,

NSString *string = @"Hello YOUR_NAME, My name is YOUR_NAME, Good day";
string = [string stringByReplacingOccurrencesOfString:@"YOUR_NAME" withString:@"Your_desired_Name"];

UPDATE

If both values are different then you can do this,

NSString *string = @"Hello %@, My name is %@, Good day";
NSString *output = [NSString stringWithFormat:string, variable1, variable2];

Upvotes: 1

Related Questions