Easiest way to concatenate NSString and int

旧城冷巷雨未停 提交于 2019-11-29 01:52:38

问题


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


回答1:


Both answers are correct. If you want to concatenate multiple strings and integers use NSMutableString's 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];



回答2:


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

That's typically how I do it.




回答3:


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.




回答4:


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.

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 ;



回答5:


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.



来源:https://stackoverflow.com/questions/703669/easiest-way-to-concatenate-nsstring-and-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!