我想在字符串中放置一个字符串。基本上在伪代码中:
"first part of string" + "(varying string)" + "third part of string"
我怎样才能在objective-c中做到这一点?有没有办法在 obj-c 中轻松连接?谢谢!
我想在字符串中放置一个字符串。基本上在伪代码中:
"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"
对于多个字符串
NSString *varyingString1 = @"hello";
NSString *varyingString2 = @"world";
NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2];
//str is now "hello world"
主题变奏曲:
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"];
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
"first part of string",
varyingString,
@"third part of string"];
或者干脆-[NSString stringByAppendingString:]
你通常会-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"
令我惊讶的是,没有一个最佳答案指出在最近的 Objective-C 版本下(在他们添加文字之后),您可以像这样连接:
@"first" @"second"
这将导致:
@"firstsecond"
您不能将它与 NSString 对象一起使用,只能与文字一起使用,但在某些情况下它可能很有用。
简单的一个:
[[@"first" stringByAppendingString:@"second"] stringByAppendingString:@"third"];
如果您有许多要连接的字符串,则应该使用NSMutableString
以获得更好的性能