问题
I am building a calculator app for iOS using DDMathParser. I would like to know how to separate an expression (NSString
) like 5+900/32
into its individual number values: 5
, 900
, and 32
. I would prefer that I get these in an NSArray
or other relatively useful list object. I have heard that there is an easy way to do this with DDMathParser
- It's why I switched from GCMathParser
.
回答1:
DDMathParser author here.
Yes, this is very easy, and there are a couple of ways to go about it. If you simply want what the numbers are and don't care about the operators, you can use the tokenizing API:
NSError *tokenizingError = nil;
DDMathStringTokenizer *tokenizer = [DDMathStringTokenizer tokenizerWithString:@"5+900/32" error:&tokenizingError];
NSArray *tokens = [tokenizer tokens];
NSMutableArray *numbers = [NSMutableArray array];
for (DDMathStringToken *token in tokens) {
if ([token tokenType] == DDTokenTypeNumber) {
[numbers addObject:[token numberValue]];
}
}
// numbers now is @[ @5, @900, @32 ];
There is, however, a caveat to this approach, and it can be best illustrated with this example: @"-42"
. Tokens in DDMathParser are always parsed as unsigned numbers, because the minus sign in front is actually an operator and gets applied differently depending on other operators. That means that if you tokenize the string @"-42"
, you'll see that it contains two tokens: a negation operator, and the number 42.
来源:https://stackoverflow.com/questions/14417462/ios-ddmathparser-get-number-blocks