Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenate nsstring and excluding nulls

I am trying to concatenate a few NSStrings but would like to exclude the ones that are nulls. I am using this solution:

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

but what if one of the string is null? I'd like to exclude it. any ideas?

thanks.

like image 463
moshikafya Avatar asked Jun 09 '26 00:06

moshikafya


1 Answers

You could do:

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

Or better would probably be to have a mutable string and build it up:

NSMutableString *string = [[NSMutableString alloc] initWithCapacity:0];
if (three) {
    [string appendFormat:@"%@/", three];
}
if (two) {
    [string appendFormat:@"%@/", two];
}
if (one) {
    [string appendFormat:@"%@/", one];
}
like image 191
mattjgalloway Avatar answered Jun 10 '26 13:06

mattjgalloway