在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 *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

在使用Objective C几年之后,我认为这是使用Objective C实现你想要实现的目标的最佳方式。

开始在你的Xcode应用中输入“N”,它自动完成为“NSString”。 key in "str",它自动补全为"stringByAppendingString"。所以按键是非常有限的。

一旦你掌握了敲击“@”键和标签的窍门,编写可读代码的过程就不再是问题了。这只是一个适应的问题。

其他回答

这样使用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."];
NSString *label1 = @"Process Name: ";
NSString *label2 = @"Process Id: ";
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
NSString *testConcat = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];

这是为了更好的日志记录,而且仅仅是日志记录——基于dicius优秀的多参数方法。我定义了一个Logger类,并像这样调用它:

[Logger log: @"foobar ", @" asdads ", theString, nil];

几乎很好,除了var args必须以“nil”结束,但我想在Objective-C中没有办法绕过它。

Logger.h

@interface Logger : NSObject {
}
+ (void) log: (id) first, ...;
@end

Logger.m

@implementation Logger

+ (void) log: (id) first, ...
{
    // TODO: make efficient; handle arguments other than strings
    // thanks to @diciu http://stackoverflow.com/questions/510269/how-do-i-concatenate-strings-in-objective-c
    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);
    }
    NSLog(@"%@", result);
}

@end 

为了只连接字符串,我在NSString上定义了一个Category,并添加了一个静态(+)连接方法,它看起来完全像上面的log方法,除了它返回字符串。它在NSString上,因为它是一个字符串方法,它是静态的,因为你想从1-N个字符串中创建一个新字符串,而不是在任何一个作为append一部分的字符串上调用它。

NSNumber *lat = [NSNumber numberWithDouble:destinationMapView.camera.target.latitude];
NSNumber *lon = [NSNumber numberWithDouble:destinationMapView.camera.target.longitude];
NSString *DesconCatenated = [NSString stringWithFormat:@"%@|%@",lat,lon];

你可以使用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];