连接nsstring并排除空值

mos*_*fya 3 iphone xcode objective-c nsstring ios

我试图连接几个NSStrings,但想排除那些空值.我正在使用这个解决方案:

[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
Run Code Online (Sandbox Code Playgroud)

但如果其中一个字符串为空呢?我想排除它.有任何想法吗?

谢谢.

mat*_*way 7

你可以这样做:

[NSString stringWithFormat:@"%@/%@/%@", three ?: @"", two ?: @"", one ?: @""];
Run Code Online (Sandbox Code Playgroud)

或者更好的方法是拥有一个可变字符串并构建它:

NSMutableString *string = [[NSMutableString alloc] initWithCapacity:0];
if (three) {
    [string appendFormat:@"%@/", three];
}
if (two) {
    [string appendFormat:@"%@/", two];
}
if (one) {
    [string appendFormat:@"%@/", one];
}
Run Code Online (Sandbox Code Playgroud)