0

我有NSString一个数学表达式。我有运算符(+,-,*,/)和操作数(digits from 0 to 9,integers,decimals etc)。我想把它转换NSStringNSArray. 例如,如果我NSString是“7.9999-1.234*-9.21”。我希望NSArray元素 7.9999,-,1.234,*,-,9.21 以相同的顺序排列。我怎样才能做到这一点?

我试过一个代码。不过,它在所有情况下都有效。这里是:

代码:

NSString *str=@"7.9999-1.234*-9.21";
NSMutableArray *marray=[[NSMutableArray alloc] init];
    for(i=0;i<6;i++)
    {
        [marray addObject:[NSNull null]];
    }
    NSMutableArray *operands=[[NSMutableArray alloc] initWithObjects:@"7.9999",@"1.234",@"9.21",nil];
    NSMutableArray *operators=[[NSMutableArray alloc] initWithObjects:@"-",@"*",@"-",nil];
    for(i=0,j=0,k=0,l=0;i<=([str length]-1),j<[operands count],k<[operators count],l<[marray count];i++)
    {
        NSString *element=[[NSString alloc] initWithFormat:@"%c",[str characterAtIndex:i]];
        BOOL res=[element isEqualToString:@"+"]||[element isEqualToString:@"-"]||[element isEqualToString:@"*"]||[element isEqualToString:@"/"];
        if(res==0)
        {
            [marray replaceObjectAtIndex:l withObject:[operands objectAtIndex:j]];


        }
        else
        {
            l++;
            [marray replaceObjectAtIndex:l withObject:[operators objectAtIndex:k]];
            k++,l++,j++;

        }
    }
    for(i=0;i<6;i++)
    {
        NSLog(@"%@",[marray objectAtIndex:i]);
    }

这里 str 是要转换的字符串。我的数组是字符串str转换得到的数组。当我执行此代码时,我在控制台上得到以下信息:

 7.9999
 -
 1.234
 *
 <null>
 -
4

3 回答 3

2

您应该使用NSScanner, 扫描到您的运算符字符,然后当您找到一个时,保存扫描的字符串,然后将运算符保存到数组中并跳过运算符 ( setScanLocation:)。继续执行此操作,直到到达字符串的末尾(在循环中,每个运算符进行一次迭代)。

于 2013-08-12T11:19:55.853 回答
0
NSArray * marray = [str componentsSeparatedByCharactersInSet:
                      [NSCharacterSet characterSetWithCharactersInString:@"+-*/"]
                    ];
于 2013-08-12T11:20:09.733 回答
0

谢谢@Wain 和@Hinata Hyuga。在您的建议的帮助下,我想出了一个可以将任何字符串转换为数组的代码。

这是代码

NSMutableArray *convArray=[[NSMutableArray alloc] init];
    NSScanner *scanner = [NSScanner scannerWithString:inputString];
    NSCharacterSet *opSet=[NSCharacterSet characterSetWithCharactersInString:@"+-/*"];
    [scanner setCharactersToBeSkipped:opSet];
    int i;
    for(i=0;i<[inputString length];)
    {
        if([inputString characterAtIndex:i]=='+'||[inputString characterAtIndex:i]=='-'||[inputString characterAtIndex:i]=='*'||[inputString characterAtIndex:i]=='/')
        {
            [convArray addObject:[[NSString alloc] initWithFormat:@"%c",[inputString characterAtIndex:i]]];
            i++;
        }
        else
        {
            NSString *oprnd;
            [scanner scanUpToCharactersFromSet:opSet intoString:&oprnd];
            [convArray addObject:oprnd];
            i=i+[inputString rangeOfString:oprnd].length;
        }
    }
    return convArray;
于 2013-08-13T06:17:39.390 回答