objective-c 连接 NSString 和 int 的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/703669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:19:37  来源:igfitidea点击:

Easiest way to concatenate NSString and int

objective-cstringcocoacocoa-touchnsstring

提问by DivideByHero

Is there a general purpose function in Objective-C that I can plug into my project to simplify concatenating NSStrings and ints?

Objective-C 中是否有通用函数可以插入到我的项目中以简化NSStrings 和ints 的连接?

回答by Genericrich

[NSString stringWithFormat:@"THIS IS A STRING WITH AN INT: %d", myInt];

That's typically how I do it.

这就是我通常的做法。

回答by Rog

Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's appendFormat.

两个答案都是正确的。如果要连接多个字符串和整数,请使用 NSMutableString 的 appendFormat。

NSMutableString* aString = [NSMutableString stringWithFormat:@"String with one int %d", myInt];    // does not need to be released. Needs to be retained if you need to keep use it after the current function.
[aString appendFormat:@"... now has another int: %d", myInt];

回答by ksnr

string1,x , these are declared as a string object and integer variable respectively. and if you want to combine both the values and to append int values to a string object and to assign the result to a new string then do as follows.

string1,x ,它们分别被声明为字符串对象和整数变量。如果您想组合这两个值并将 int 值附加到字符串对象并将结果分配给新字符串,请执行以下操作。

NSString *string1=@"Hello"; 

int x=10;

NSString *string2=[string1 stringByAppendingFormat:@"%d ",x];

NSLog(@"string2 is %@",string2);


//NSLog(@"string2 is %@",string2); is used to check the string2 value at console ;

回答by Pablo Santa Cruz

NSString *s = 
   [
       [NSString alloc] 
           initWithFormat:@"Concatenate an int %d with a string %@", 
            12, @"My Concatenated String"
   ];

I know you're probably looking for a shorter answer, but this is what I would use.

我知道您可能正在寻找更简短的答案,但这就是我会使用的。

回答by vanangelov

It seems the real answer is no - there is no easy and short way to concatenate NSStrings with Objective C - nothing similar to using the '+' operator in C# and Java.

似乎真正的答案是否定的 - 没有简单快捷的方法将 NSStrings 与 Objective C 连接起来 - 没有什么类似于在 C# 和 Java 中使用“+”运算符。