iOS DDMathParser获取数字'块' [英] iOS DDMathParser Get Number 'Blocks'

查看:132
本文介绍了iOS DDMathParser获取数字'块'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DDMathParser为iOS构建一个计算器应用程序。 我想知道如何将一个表达式( NSString )与 5 + 900/32 个人编号值: 5 900 32 我希望我可以使用 NSArray 或其他相对有用的列表对象。我听说有一个简单的方法可以用 DDMathParser 这样做 - 这就是为什么我从 GCMathParser p>

解决方案

DDMathParser作者在这里。



是的,这很容易,有几种方法可以解决。如果您只想要数字,而不关心运算符,则可以使用令牌化 API:

  NSError * tokenizingError = nil; 
DDMathStringTokenizer * tokenizer = [DDMathStringTokenizer tokenizerWithString:@5 + 900/32错误:& tokenizingError];
NSArray * tokens = [tokenizer令牌];

NSMutableArray * numbers = [NSMutableArray array];
for(DDMathStringToken * token in tokens){
if([token tokenType] == DDTokenTypeNumber){
[numbers addObject:[token numberValue]];
}
}

//现在的数字是@ [@ 5,@ 900,@ 32];

然而,这个方法有一个警告,可以用这个例子来说明最好的例子: @ - 42。 DDMathParser中的令牌始终被解析为无符号号,因为前面的减号实际上是一个运算符,并根据其他运算符得到不同的应用。这意味着如果你标记字符串 @ - 42,你会看到它包含两个标记:一个否定运算符, 42号。


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.

解决方案

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.

这篇关于iOS DDMathParser获取数字'块'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆