Objective C : Find number of operators in a mathematical string

90 views Asked by At

I'm using the following technique to find the number of operators in a mathematical string.

for (int index = 0; index < [self.evaluateString length]; index++) {
    unichar chars = [self.evaluateString characterAtIndex:index];
    if (chars == '+' || chars == '-' || chars == '*' || chars == '/' ||chars == '^') {
        self.operatorCount++;
    }
}

My trainer says this method is not very good. I would like to know is there any better/more elegant method to do this. Thanks.

2

There are 2 answers

2
Avi On

You can do something like this. It's not particularly efficient, compared to your code, but it looks fancy.

NSString *s = @"3 + 1 - 2 * 4 / 4";

NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"+-*/"] invertedSet];

NSArray *a = [[s componentsSeparatedByCharactersInSet:cs] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];

NSLog(@"%lu", a.count);

The NSLog() will print 4, as expected.

The algorithm is simple:

  1. Create a character set that is the inverse of the operator list.
  2. Split the expression string by the inverted character set.
  3. Filter out elements of zero length.

The remaining elements in the array will be the operators. The count of elements in the array is the count of operators in the expression.

1
Nikolai Ruhe On

It seems that string is to be evaluated. Part of that evaluation is parsing. During this process mathematical operators are identified and could be counted.

The advantage over simple character counting would be to tell apart a 3 - 1 (operator) from a -1 (negative number literal).