在NSString中包含一个变量?

rs1*_*ith 4 objective-c string-concatenation string-formatting nsstring

这很好,我们都知道:

NSString *textoutput = @"Hello";
outLabel.text = textoutput;
Run Code Online (Sandbox Code Playgroud)

但是,如果要在该NSString语句中包含变量,如下所示:

NSString *textoutput =@"Hello" Variable;
Run Code Online (Sandbox Code Playgroud)

在C++中我知道什么时候我cout想要包含一个变量我所做的就像这样:

cout << "Hello" << variableName << endl;
Run Code Online (Sandbox Code Playgroud)

所以我试图用Objective-C来实现它,但我不知道如何实现.

Rav*_*mio 15

您可以使用以下功能进行一些奇特的格式化:

NSString *textoutput = [NSString stringWithFormat:@"Hello %@", variable];
Run Code Online (Sandbox Code Playgroud)

请注意,%@假设它variable是Objective-C对象.如果它是C字符串,请使用%s,如果是任何其他C类型,请查看printf引用.

或者,您可以通过将字符串附加到现有字符串来创建新字符串:

NSString *hello = @"Hello";
NSString *whatever = [hello stringByAppendingString:@", world!"];
Run Code Online (Sandbox Code Playgroud)

请注意,这NSString是不可变的 - 一旦分配了值,就无法更改它,只能派生新对象.如果你要在字符串中添加很多内容,你应该使用它NSMutableString.


Jor*_*nas 5

罗伯特史密斯:我有你正在寻找的治疗方法:

如果您的变量是对象,请使用:
NSString *textOutput = [NSString stringWithFormat:@"Hello %@", Variable];

'%@'仅适用于对象.对于整数,它是'%i'.

对于其他类型,或者如果您希望对其生成的字符串更具特异性,请使用本指南

  • 哇,没有人注意到我的双关语. (2认同)