52

我想在字符串中放置一个字符串。基本上在伪代码中:

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

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

4

7 回答 7

121

是的

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"
于 2012-08-15T15:11:12.430 回答
13

主题变奏曲:

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"];
于 2012-08-15T15:11:52.200 回答
10
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
  "first part of string",
  varyingString,
  @"third part of string"];

或者干脆-[NSString stringByAppendingString:]

于 2012-08-15T15:11:39.530 回答
6

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

NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];
于 2012-08-15T15:11:11.853 回答
3

做就是了

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

这给你

@"first part of string (foo) third part of string"
于 2012-08-15T15:11:46.333 回答
3

令我惊讶的是,没有一个最佳答案指出在最近的 Objective-C 版本下(在他们添加文字之后),您可以像这样连接:

@"first" @"second"

这将导致:

@"firstsecond"

您不能将它与 NSString 对象一起使用,只能与文字一起使用,但在某些情况下它可能很有用。

于 2017-10-03T03:52:29.390 回答
1

简单的一个:

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

如果您有许多要连接的字符串,则应该使用NSMutableString以获得更好的性能

于 2012-08-15T16:08:56.703 回答