在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";
你可以使用NSArray as
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
or
你可以使用
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
当我测试时,这两种格式都可以在XCode7中工作:
NSString *sTest1 = {@"This" " and that" " and one more"};
NSString *sTest2 = {
@"This"
" and that"
" and one more"
};
NSLog(@"\n%@\n\n%@",sTest1,sTest2);
出于某种原因,您只需要在混合的第一个字符串上使用@操作符。
但是,它不能用于变量插入。为此,您可以使用这个极其简单的解决方案,除了对“cat”而不是“and”使用宏。
这样使用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."];