【问题标题】:NSString Detect Number then ParenthesisNSString 检测数字然后括号
【发布时间】:2013-01-01 13:41:15
【问题描述】:

我正在制作一个 iOS 计算器应用程序。我希望能够在字符串中找到相邻的数字字符和括号的出现,例如这些示例:

  • 23(8+9)
  • (89+2)(78)
  • (7+8)9

我希望能够在这些事件之间插入一个字符:

  • 23(8+9) 将是 23*(8+9)
  • (89+2)(78) 将是 (89+2)*(78)
  • (7+8)9 将是 (7+8)*9

【问题讨论】:

  • 你的第一个例子不会改变表达式的含义吗?
  • 似乎适合 DDMathParser 的任务。

标签: ios ipad nsstring formatting calculator


【解决方案1】:

这是我编写的一个快速函数,它使用正则表达式来查找匹配的模式,然后在需要的地方插入一个“*”。例如,它匹配两个括号“)(”或一个数字和括号“5(”或“)3”。如果中间有空格,例如“)5”,它也可以工作。

随意调整功能以满足您的需求。不确定这是否是最好的方法,但它确实有效。

有关正则表达式的更多信息,请参阅documentation for NSRegularExpression

- (NSString *)stringByInsertingMultiplicationSymbolInString:(NSString *)equation {
    // Create a mutable copy so we can manipulate it
    NSMutableString *mutableEquation = [equation mutableCopy];

    // The regexp pattern matches:
    // ")(" or "n(" or ")n"  (where n is a number).
    // It also matches if there's whitepace in between (eg. (4+5)  (2+3) will work)
    NSString *pattern = @"(\\)\\s*?\\()|(\\d\\s*?\\()|(\\)\\s*?\\d)";

    NSError *error;
    NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regexp matchesInString:equation options:NSMatchingReportProgress range:NSMakeRange(0, [equation length])];

    // Keep a counter so that we can offset the index as we go
    NSUInteger count = 0;
    for (NSTextCheckingResult *match in matches) {
        [mutableEquation insertString:@"*" atIndex:match.range.location+1+count];
        count++;
    }

    return mutableEquation;
}

这是我测试它的方式:

NSString *result;

result = [self stringByInsertingMultiplicationSymbolInString:@"23(8+9)"];
NSLog(@"Result: %@", result);

result = [self stringByInsertingMultiplicationSymbolInString:@"(89+2)(78)"];
NSLog(@"Result: %@", result);

result = [self stringByInsertingMultiplicationSymbolInString:@"(7+8)9"];
NSLog(@"Result: %@", result);

这将输出:

Result: 23*(8+9)
Result: (89+2)*(78)
Result: (7+8)*9

注意:此代码使用 ARC,因此如果您使用 MRC,请记住自动释放复制的字符串。

【讨论】:

  • 哇!惊人的!我要使用 DDMathParser,但你被标记为正确!
猜你喜欢
  • 2013-06-12
  • 2020-04-18
  • 2015-05-01
  • 2011-10-10
  • 2011-09-04
  • 2017-05-26
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多