Concatenate nsstring and eliminate zeros

I am trying to combine multiple NSStrings, but would like to exclude those that are zeros. I am using this solution:

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

but what if one of the lines is zero? I would like to rule that out. any ideas?

thank.

+3
source share
3 answers

You can do:

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

Or better, it would probably have a mutable string and create it:

NSMutableString *string = [[NSMutableString alloc] initWithCapacity:0];
if (three) {
    [string appendFormat:@"%@/", three];
}
if (two) {
    [string appendFormat:@"%@/", two];
}
if (one) {
    [string appendFormat:@"%@/", one];
}
+7
source

You can only have a method

- (NSString *)stringOrEmptyString:(NSString *)string
{
    if (string)
        return string;
    else
        return @"";
}

and then just

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

Update:

Alternatively, if you do not want to have slashes, if there were empty values, you could do something like:

NSMutableArray *array = [[NSMutableArray alloc] init];

if (one)
    [array addObject:one];
if (two)
    [array addObject:two];
if (three)
    [array addObject:three];

Then you can get the NSString result with something like:

[array componentsJoinedByString:@"/"]

, , , ARC, [array release].

+3

.

NSString *myString = [[NSString alloc] init];
NSArray *myObjects = [[NSArray alloc] initWithObjects:three,two,one,nil];
for(NSString *currentObject in myObjects) {
    if(![currentObject isEqualToString:@""]) myString = [NSString stringWithFormat:@"%@/%@",myString,currentObject];
}
+1

All Articles