在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];

其他回答

NSString *myString = @"This";
NSString *test = [myString stringByAppendingString:@" is just a test"];

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

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

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

如果你有两个NSString字面量,你也可以这样做:

NSString *joinedFromLiterals = @"ONE " @"MILLION " @"YEARS " @"DUNGEON!!!";

这对于加入#定义也很有用:

#define STRINGA @"Also, I don't know "
#define STRINGB @"where food comes from."
#define JOINED STRINGA STRINGB

享受。

一个选项:

[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 *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];

正在尝试在lldb窗格中执行以下操作

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

这错误。

而是使用alloc和initWithFormat方法:

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