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.
You can do something like this. It's not particularly efficient, compared to your code, but it looks fancy.
The
NSLog()
will print 4, as expected.The algorithm is simple:
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.