在string中连接stringObjective-c

我想在一个string中放置一个string。 基本上是伪代码:

"first part of string" + "(varying string)" + "third part of string" 

我怎样才能在objective-c中做到这一点? 有没有办法在obj-c中轻松地连接? 谢谢!

是的

 NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString]; 

串联可以使用stringByAppendingString

 NSString *str = @"hello "; str = [str stringByAppendingString:@"world"]; //str is now "hello world" 

对于多个string

 NSString *varyingString1 = @"hello"; NSString *varyingString2 = @"world"; NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2]; //str is now "hello world" 
 NSString * varyingString = ...; NSString * cat = [NSString stringWithFormat:@"%s%@%@", "first part of string", varyingString, @"third part of string"]; 

或者干脆-[NSString stringByAppendingString:]

一个主题的变化:

 NSString *varying = @"whatever it is"; NSString *final = [NSString stringWithFormat:@"first part %@ third part", varying]; 

 NSString *varying = @"whatever it is"; NSString *final = [[@"first part" stringByAppendingString:varying] stringByAppendingString:@"second part"]; 

 NSMutableString *final = [NSMutableString stringWithString:@"first part"]; [final appendFormat:@"%@ third part", varying]; 

 NSMutableString *final = [NSMutableString stringWithString:@"first part"]; [final appendString:varying]; [final appendString:@"third part"]; 

你通常-stringWithFormat在这里使用-stringWithFormat

 NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"]; 

做就是了

 NSString* newString=[NSString stringWithFormat:@"first part of string (%@) third part of string", @"foo"]; 

这给你

 @"first part of string (foo) third part of string" 

简单的一个:

 [[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"]; 

如果你有很多STRESS连接,你应该使用NSMutableString来获得更好的性能

Iam惊讶地发现,在最近的Objective-C版本(他们添加文字之后)中没有一个答案指出,你可以像这样连接:

 @"first" @"second" 

这将导致:

 @"firstsecond" 

你不能在NSString对象中使用它,只能使用文字,但在某些情况下它可能是有用的。