3

How can I concatenate two numbers like 7 and 6 to result in the number 76, or 3 and 3 so the result is 33, in objective-c?

Duncan Babbage
  • 19,972
  • 4
  • 56
  • 93
Flocked
  • 1,898
  • 2
  • 36
  • 57

5 Answers5

16

There is no built in symbol to concatenate numbers. However, you can accomplish this by doing:

int first; /* Assuming this is initialized to the first number */
int second; /* Assuming this is initalized to the second number */
int myVal = [[NSString stringWithFormat:@"%d%d",first, second] intValue];
Mike
  • 23,892
  • 18
  • 70
  • 90
  • Parsing format strings is expensive. Use -stringByAppendingString: when you can. – NSResponder Jan 03 '10 at 04:23
  • 2
    That would require two separate memory allocations, which could be more expensive than parsing this (simple) format expression string. At any rate, I don't think the performance of either method will be a huge issue. – Mike Jan 03 '10 at 04:26
  • 1
    Agreed here with Mike. The complexity of setting up two strings from integers and concatenating them is unlikely to be better than the +stringWithFormat for this problem. It would certainly require profiling to know for certain, since the other common way, using NSNumber -stringValue, could be even more expensive. Even if you already had the strings, I'd be very curious of the actual cost of +stringWithFormat versus -stringByAppendingString, especially in the case of more than 2 elements, and only profiling would tell us. Cocoa makes no promises about efficiency in either case. – Rob Napier Jan 03 '10 at 04:40
5

FirstNum * 10 + secondNum :-)

Matt
  • 450
  • 1
  • 4
  • 11
2

That's not a numeric operation, it's string concatenation.

Shortcuts in Objective-C to concatenate NSStrings

Community
  • 1
  • 1
ceejayoz
  • 176,543
  • 40
  • 303
  • 368
1

If you want two numbers x and y to add to xy, you can do

10*x + y.

For 7 and 6

7*10 + 6 = 76

jkeesh
  • 3,289
  • 3
  • 29
  • 42
0

I don't know much about objective-c but I would say:

  • If you get the numbers from an array, like nums= array(7,6), initialize result= 0 and then do a foreach on them. For each value you find, do : res= res*10 + value. At the end, even if you got 7 numbers to concatenate you'll get the result right. ie:

    Array nums= Array(7,6,8,9); int res= 0; int value; foreach (value in nums) res= res*10 + value;

  • If you can use strings, just concatenate them like suggested above. there is probably a function to concatenate all values from an array as well to make it flexible.

Hope it helps

C^

acerb
  • 76
  • 4