Easiest way to concatenate NSString and int

63,459

Solution 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];

Solution 2

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

That's typically how I do it.

Solution 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.

Solution 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 ;
Share:
63,459
DivideByHero
Author by

DivideByHero

Updated on February 29, 2020

Comments

  • DivideByHero
    DivideByHero about 4 years

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