Haagenti
Haagenti

Reputation: 8154

iOS string expression to integer value

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?

Upvotes: 0

Views: 163

Answers (3)

iPatel
iPatel

Reputation: 47119

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

Upvotes: 0

Martin R
Martin R

Reputation: 540105

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.

Upvotes: 15

peko
peko

Reputation: 11335

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

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

Upvotes: 2

Related Questions