- (NSString *)calcString:(NSString *)mathString
{
int sum=0;
NSMutableString *strOperator=[[NSMutableStringalloc] init];
NSMutableString *strOperand=[[NSMutableStringalloc] init];
NSMutableArray *arrOperand=[mathStringcomponentsSeparatedByCharactersInSet:[NSCharacterSetcharacterSetWithCharactersInString:@"+-/*"]];
NSMutableArray *arrOperator=[mathStringcomponentsSeparatedByCharactersInSet:[NSCharacterSetcharacterSetWithCharactersInString:@"0123456789 "]];
int f1=(int)[mathStringcharacterAtIndex:0];
if (f1>48&&f1<57) {//第一个字母是数字
[arrOperatorremoveObjectAtIndex:0];
[arrOperatorremoveLastObject];
}else
{//第一个字母是运算符
[arrOperandremoveObjectAtIndex:0];
[arrOperand insertObject:[NSStringstringWithFormat:@"0"]atIndex:0];
[arrOperatorremoveLastObject];
}
for(int i=0;i<[arrOperatorcount];i++)
{
if ([[arrOperator objectAtIndex:i] compare:@""]==NSOrderedSame) {
[arrOperatorremoveObjectAtIndex:i];
i=-1;
}
}
// NSLog(@"%@",arrOperand);
// NSLog(@"%@",arrOperator);
while ([arrOperator count]) {
for (int i=0; i<[arrOperatorcount]; i++) {
//先运算符中的*、/
if ([[arrOperator objectAtIndex:i] characterAtIndex:0]=='*') {
//计算运算符'*'两边的数字
int count=
[[arrOperandobjectAtIndex:i] intValue]*([[arrOperandobjectAtIndex:i+1]intValue]);
// NSLog(@"%d-%d-%d",[[arrOperand objectAtIndex:i] intValue],[[arrOperand objectAtIndex:i+1] intValue],i);
NSRange range={i,2};
[arrOperandremoveObjectsInRange:range];
[arrOperandinsertObject:[NSStringstringWithFormat:@"%d",count]atIndex:i];
[arrOperatorremoveObjectAtIndex:i];
// NSLog(@"%@",arrOperand);
// NSLog(@"%@",arrOperator);
i=-1;//从头检测
}elseif([[arrOperator objectAtIndex:i]characterAtIndex:0]=='/')
{
int count=
([[arrOperandobjectAtIndex:i] intValue])/([[arrOperandobjectAtIndex:i+1]intValue]);
//计算运算符'/'两边的数字
NSRange range={i,2};
[arrOperandremoveObjectsInRange:range];
[arrOperandinsertObject:[NSStringstringWithFormat:@"%d",count]atIndex:i];
[arrOperatorremoveObjectAtIndex:i];
i=-1;//从头检测
}
}
for (int i=0; i<[arrOperatorcount]; i++) {
if([[arrOperator objectAtIndex:i]characterAtIndex:0]=='-')
{
//计算运算符'-'两边的数字
int count=
([[arrOperandobjectAtIndex:i] intValue])-([[arrOperandobjectAtIndex:i+1]intValue]);
NSRange range={i,2};
[arrOperandremoveObjectsInRange:range];
[arrOperandinsertObject:[NSStringstringWithFormat:@"%d",count]atIndex:i];
[arrOperatorremoveObjectAtIndex:i];
i=-1;
}elseif ([[arrOperator objectAtIndex:i] characterAtIndex:0]=='+') {
//计算运算符'+'两边的数字
int count=
([[arrOperandobjectAtIndex:i] intValue])+([[arrOperandobjectAtIndex:i+1]intValue]);
NSRange range={i,2};
[arrOperandremoveObjectsInRange:range];
[arrOperandinsertObject:[NSStringstringWithFormat:@"%d",count]atIndex:i];
[arrOperatorremoveObjectAtIndex:i];
i=-1;
}
}
}
return [arrOperand objectAtIndex:0];
}