Are there any shortcuts to (stringByAppendingString:
) string concatenation in Objective-C, or shortcuts for working with NSString
in general?
Macro:
// stringConcat(...)
// A shortcut for concatenating strings (or objects' string representations).
// Input: Any number of non-nil NSObjects.
// Output: All arguments concatenated together into a single NSString.
#define stringConcat(...) \
[@[__VA_ARGS__] componentsJoinedByString:@""]
Test Cases:
- (void)testStringConcat {
NSString *actual;
actual = stringConcat(); //might not make sense, but it's still a valid expression.
STAssertEqualObjects(@"", actual, @"stringConcat");
actual = stringConcat(@"A");
STAssertEqualObjects(@"A", actual, @"stringConcat");
actual = stringConcat(@"A", @"B");
STAssertEqualObjects(@"AB", actual, @"stringConcat");
actual = stringConcat(@"A", @"B", @"C");
STAssertEqualObjects(@"ABC", actual, @"stringConcat");
// works on all NSObjects (not just strings):
actual = stringConcat(@1, @" ", @2, @" ", @3);
STAssertEqualObjects(@"1 2 3", actual, @"stringConcat");
}
Alternate macro: (if you wanted to enforce a minimum number of arguments)
// stringConcat(...)
// A shortcut for concatenating strings (or objects' string representations).
// Input: Two or more non-nil NSObjects.
// Output: All arguments concatenated together into a single NSString.
#define stringConcat(str1, str2, ...) \
[@[ str1, str2, ##__VA_ARGS__] componentsJoinedByString:@""];
How about shortening stringByAppendingString
and use a #define:
#define and stringByAppendingString
Thus you would use:
NSString* myString = [@"Hello " and @"world"];
Problem is that it only works for two strings, you're required to wrap additional brackets for more appends:
NSString* myString = [[@"Hello" and: @" world"] and: @" again"];
When dealing with strings often I find it easier to make the source file ObjC++, then I can concatenate std::strings using the second method shown in the question.
std::string stdstr = [nsstr UTF8String];
//easier to read and more portable string manipulation goes here...
NSString* nsstr = [NSString stringWithUTF8String:stdstr.c_str()];
Was trying the following in the lldb
pane
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
which errors.
instead use alloc and initWithFormat
method:
[[NSString alloc] initWithFormat:@"%@/%@/%@", @"three", @"two", @"one"];
Let's imagine that u don't know how many strings there.
NSMutableArray *arrForStrings = [[NSMutableArray alloc] init];
for (int i=0; i<[allMyStrings count]; i++) {
NSString *str = [allMyStrings objectAtIndex:i];
[arrForStrings addObject:str];
}
NSString *readyString = [[arrForStrings mutableCopy] componentsJoinedByString:@", "];
Two answers I can think of... neither is particularly as pleasant as just having a concatenation operator.
First, use an NSMutableString
, which has an appendString
method, removing some of the need for extra temp strings.
Second, use an NSArray
to concatenate via the componentsJoinedByString
method.