如何将NSString转换为NSArray?

时间:2013-08-12 11:13:11

标签: objective-c nsstring nsmutablearray

我有NSString这是一个数学表达式。我有运算符(+,-,*,/)和操作数(digits from 0 to 9,integers,decimals etc)。我想将此NSString转换为NSArray。例如,如果我的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>
 -

3 个答案:

答案 0 :(得分:2)

您应该使用NSScanner,扫描到您的操作员字符,然后找到一个,保存扫描的字符串,然后将操作符保存到数组中并跳过操作符(setScanLocation:)。继续这样做直到你到达字符串的末尾(循环中,每个操作符一次迭代)。

答案 1 :(得分:0)

NSArray * marray = [str componentsSeparatedByCharactersInSet:
                      [NSCharacterSet characterSetWithCharactersInString:@"+-*/"]
                    ];

答案 2 :(得分: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;