在Objective-C中有没有(stringByAppendingString:)字符串连接的快捷方式,或者一般使用NSString的快捷方式?
例如,我想做:
NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];
更像是:
string myString = "This";
string test = myString + " is just a test";
一个选项:
[NSString stringWithFormat:@"%@/%@/%@", one, two, three];
另一个选择:
我猜你不满意多个追加(a+b+c+d),在这种情况下,你可以这样做:
NSLog(@"%@", [Util append:one, @" ", two, nil]); // "one two"
NSLog(@"%@", [Util append:three, @"/", two, @"/", one, nil]); // three/two/one
使用类似于
+ (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;
}
我喜欢的方法是:
NSString *firstString = @"foo";
NSString *secondString = @"bar";
NSString *thirdString = @"baz";
NSString *joinedString = [@[firstString, secondString, thirdString] join];
你可以通过在NSArray中添加join方法来实现:
#import "NSArray+Join.h"
@implementation NSArray (Join)
-(NSString *)join
{
return [self componentsJoinedByString:@""];
}
@end
@[]是NSArray的简短定义,我认为这是连接字符串最快的方法。
如果你不想使用类别,直接使用componentsJoinedByString:方法:
NSString *joinedString = [@[firstString, secondString, thirdString] componentsJoinedByString:@""];
我一直在看这篇文章,最后总是整理答案,找到一个简单的解决方案,可以根据需要处理尽可能多的变量:
[NSString stringWithFormat:@"%@/%@/%@", three, two, one];
例如:
NSString *urlForHttpGet = [NSString stringWithFormat:@"http://example.com/login/username/%@/userid/%i", userName, userId];
这样使用stringByAppendingString:
NSString *string1, *string2, *result;
string1 = @"This is ";
string2 = @"my string.";
result = [result stringByAppendingString:string1];
result = [result stringByAppendingString:string2];
OR
result = [result stringByAppendingString:@"This is "];
result = [result stringByAppendingString:@"my string."];