连接字符串Objective-c中的字符串

2020/12/08 18:31 · ios ·  · 0评论

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

"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"

Iam感到惊讶,最重要的答案都没有指出在最新的Objective-C版本(添加文字后)下,您可以像这样进行连接:

@"first" @"second"

它将导致:

@"firstsecond"

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

简单的一个:

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

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

本文地址:http://ios.askforanswer.com/lianjiezifuchuanobjective-czhongdezifuchuan.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!