在NSString的中间包含一个变量

时间:2018-05-09 05:40:18

标签: objective-c

我目前试图使用它:

NSString *hello = @"Hello";
NSString *whatever = [hello stringByAppendingString:@", world!"];

它可以使用它,但它会做很多工作,因为我的目标是做这样的事情:

NSString = "Hello" +variable+ "My name is" +variable + ",Good day"

3 个答案:

答案 0 :(得分:2)

您可以使用NSString的方法stringWithFormat

示例

NSString *str = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",var1,var2]

NSString *str = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",@"Stack Overflow",@"FreelancsAndroidLovesyou"]

答案 1 :(得分:1)

如果两个值相同,您可以选择执行此操作,

NSString *string = @"Hello YOUR_NAME, My name is YOUR_NAME, Good day";
string = [string stringByReplacingOccurrencesOfString:@"YOUR_NAME" withString:@"Your_desired_Name"];

<强>更新

如果两个值都不同,那么你可以这样做,

NSString *string = @"Hello %@, My name is %@, Good day";
NSString *output = [NSString stringWithFormat:string, variable1, variable2];

答案 2 :(得分:0)

您可以使用NSString方法stringWithFormat。

目标C

NSString *strConcat = [NSString stringWithFormat:@"Hello %@ My Name is %@ ",var1,var2];

夫特

let strConcat = "Hello "+ strOne + " My Name is " + strTwo

OR

let strConcateSecond = "Hello \(strOne) My Name is \(strTwo)"