Home:ALL Converter>Concatenate String in String Objective-c

Concatenate String in String Objective-c

Ask Time:2012-08-15T23:09:08         Author:jsttn

Json Formatter

I want to place a string within a string. Basically in pseudo code:

"first part of string" + "(varying string)" + "third part of string"

How can I do this in objective-c? Is there a way to easily concatenate in obj-c? Thanks!

Author:jsttn,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/11971945/concatenate-string-in-string-objective-c
user529758 :

Variations on a theme:\n\nNSString *varying = @\"whatever it is\";\nNSString *final = [NSString stringWithFormat:@\"first part %@ third part\", varying];\n\n\n\n\nNSString *varying = @\"whatever it is\";\nNSString *final = [[@\"first part\" stringByAppendingString:varying] stringByAppendingString:@\"second part\"];\n\n\n\n\nNSMutableString *final = [NSMutableString stringWithString:@\"first part\"];\n[final appendFormat:@\"%@ third part\", varying];\n\n\n\n\nNSMutableString *final = [NSMutableString stringWithString:@\"first part\"];\n[final appendString:varying];\n[final appendString:@\"third part\"];\n",
2012-08-15T15:11:52
justin :

NSString * varyingString = ...;\nNSString * cat = [NSString stringWithFormat:@\"%s%@%@\",\n \"first part of string\",\n varyingString,\n @\"third part of string\"];\n\n\nor simply -[NSString stringByAppendingString:]",
2012-08-15T15:11:39
Bill Burgess :

You would normally use -stringWithFormat here.\n\nNSString *myString = [NSString stringWithFormat:@\"%@%@%@\", @\"some text\", stringVariable, @\"some more text\"];\n",
2012-08-15T15:11:11
Yuji :

Just do\n\nNSString* newString=[NSString stringWithFormat:@\"first part of string (%@) third part of string\", @\"foo\"];\n\n\nThis gives you \n\n@\"first part of string (foo) third part of string\"\n",
2012-08-15T15:11:46
Rodrigo :

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:\n\n@\"first\" @\"second\"\n\n\nAnd it will result in:\n\n@\"firstsecond\"\n\n\nYou can not use it with NSString objects, only with literals, but it can be useful in some cases.",
2017-10-03T03:52:29
Dustin :

Yes, do \n\nNSString *str = [NSString stringWithFormat: @\"first part %@ second part\", varyingString];\n\n\nFor concatenation you can use stringByAppendingString\n\nNSString *str = @\"hello \";\nstr = [str stringByAppendingString:@\"world\"]; //str is now \"hello world\"\n\n\nFor multiple strings\n\nNSString *varyingString1 = @\"hello\";\nNSString *varyingString2 = @\"world\";\nNSString *str = [NSString stringWithFormat: @\"%@ %@\", varyingString1, varyingString2];\n//str is now \"hello world\"\n",
2012-08-15T15:11:12
yy