Shortcuts in Objective-C to concatenate NSStrings

前端 未结 30 2608
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 07:03

Are there any shortcuts to (stringByAppendingString:) string concatenation in Objective-C, or shortcuts for working with NSString in general?

30条回答
  •  无人及你
    2020-11-22 08:05

    An option:

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

    Another option:

    I'm guessing you're not happy with multiple appends (a+b+c+d), in which case you could do:

    NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two"
    NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one
    

    using something like

    + (NSString *) append:(id) first, ...
    {
        NSString * result = @"";
        id eachArg;
        va_list alist;
        if(first)
        {
            result = [result stringByAppendingString:first];
            va_start(alist, first);
            while (eachArg = va_arg(alist, id)) 
            result = [result stringByAppendingString:eachArg];
            va_end(alist);
        }
        return result;
    }
    

提交回复
热议问题