0

I got a string: "1+2+3232+4" which I would like to turn the answer: 3239.

How do I do this in Objective-C?

1
  • 1
    Only addition ? A way to do it, would be to use componentsSeparatedByString which return a NSArray, do the addition, and then convert into an int. Commented Sep 5, 2013 at 13:36

3 Answers 3

15

For simple expressions, you can use NSExpression:

NSExpression *e = [NSExpression expressionWithFormat:@"1+2+3232+4"];
NSNumber *result = [e expressionValueWithObject:nil context:nil];
NSLog(@"%@", result);

For more complicated expression, you should use a proper math expression parser, e.g. https://github.com/davedelong/DDMathParser.

Remark: One potential problem with this approach can be that integers are not automatically converted to floating point numbers. For example, "4/3" evaluates to 1, not to 1.3333333.

Sign up to request clarification or add additional context in comments.

Comments

2
NSString *string = @"1+2+3232+4";
NSArray *array = [string componentsSeparatedByString:@"+"];

NSInteger result = 0;
for (NSString *value in array)
   result += [value integerValue];
NSLog(@"%i", result);

1 Comment

Just a remark: You could also use Key-Value Coding to compute the sum: NSNumber *sum = [array valueForKeyPath:@"@sum.self"];
0

This is use for float/int Value also

NSString *myStringNumber = @"5+1+2+3.5+4/5+3.5*86";
NSArray *convertNumber = [myStringNumber componentsSeparatedByString:@"+"];
float sumValue = 0;
for (NSString *number in convertNumber) {
   sumValue += [number floatValue];
}
NSLog(@"Result is : %f", sumValue); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.