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?
-
1That's not adding, that's concatenation. – Mark Byers Jan 03 '10 at 04:15
-
Edit to reflect the original intention. – Duncan Babbage Nov 11 '11 at 09:41
5 Answers
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];

- 23,892
- 18
- 70
- 90
-
Parsing format strings is expensive. Use -stringByAppendingString: when you can. – NSResponder Jan 03 '10 at 04:23
-
2That 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
-
1Agreed 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
That's not a numeric operation, it's string concatenation.
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

- 3,289
- 3
- 29
- 42
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^

- 76
- 4