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";
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.
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.
[NSString stringWithFormat:@"%@/%@/%@", one, two, three];
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With