NSPredicate * parsed = [NSPredicate predicateWithFormat:@"123+456+678-985 = 0"];
NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
NSNumber * result = [left expressionValueWithObject:nil context:nil];
float i = [result floatValue];
can I convert + as an NSString to addition operator directly?
-
04-06-2022 - |
문제
I have a mathematical equation in string format.
Is there a way to convert @"+"(String constant) directly to addition operator in objective C Or
I have to use If-Else statements to solve this equation ??
해결책
다른 팁
if([yourString isEqualToString:@"+"])
{
//Do something
}
This code should work.
You can use NSExpression to achieve this
NSString *expressionFormat = [NSString stringWithFormat:@"(%d %@ %d)",firstNumber,arcthimaticOperator,secondNumber];
NSExpression *expression = [NSExpression expressionWithFormat:expressionFormat];
NSNumber *result = [expression expressionValueWithObject:nil context:nil];
NSLog(@"%@", result);
Please make sure you enter the correct format else the above code will throw exception.
제휴하지 않습니다 StackOverflow