Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcuts in Objective-C to concatenate NSStrings

Are there any shortcuts to (stringByAppendingString:) string concatenation in Objective-C, or shortcuts for working with NSString in general?

For example, I'd like to make:

NSString *myString = @"This"; NSString *test = [myString stringByAppendingString:@" is just a test"]; 

something more like:

string myString = "This"; string test = myString + " is just a test"; 
like image 323
typeoneerror Avatar asked Feb 04 '09 06:02

typeoneerror


People also ask

How do you concatenate 2 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do you concatenate variables?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect.


1 Answers

An option:

[NSString stringWithFormat:@"%@/%@/%@", one, two, three]; 

Another option:

I'm guessing you're not happy with multiple appends (a+b+c+d), in which case you could do:

NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two" NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one 

using something like

+ (NSString *) append:(id) first, ... {     NSString * result = @"";     id eachArg;     va_list alist;     if(first)     {         result = [result stringByAppendingString:first];         va_start(alist, first);         while (eachArg = va_arg(alist, id))          result = [result stringByAppendingString:eachArg];         va_end(alist);     }     return result; } 
like image 140
diciu Avatar answered Sep 22 '22 00:09

diciu