开发者

How to concatenate two numbers in Objective-C

How can I concatenate two numbers li开发者_如何学Pythonke 7 and 6 to result in the number 76, or 3 and 3 so the result is 33, in objective-c?


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


FirstNum * 10 + secondNum :-)


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

Shortcuts in Objective-C to concatenate NSStrings


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


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^

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜