Rabin Joshi
Rabin Joshi

Reputation: 33

Macro to concatenate variable number of strings

I wrote this to concatenate two strings:

#define Append(x, y) [NSString stringWithFormat:@"%@%@",x,y]

However, what if I have more than just two NSString objects. Is there way to modify this to work for any number of string values?

Upvotes: 2

Views: 1049

Answers (1)

Jay Slupesky
Jay Slupesky

Reputation: 1913

Does it have to be a macro? If you can use a method, how about this:

- (NSString*)concatenateStrings:(NSString*)string, ...
{
    NSString* result = string;

    va_list args;
    va_start(args,string);

    NSString* arg;
    while((arg = va_arg(args,NSString*)))
        result = [result stringByAppendingString:arg];

    va_end(args);

    return result;
}

Which you would call with something like:

NSString* result = [self concatenateStrings:@"ABC",@"DEF",@"GHI",nil];

Remember to terminate the argument list with a nil.

Upvotes: 3

Related Questions