如何将 NSString 转换为 NSArray? [英] How to convert NSString intoNSArray?

查看:85
本文介绍了如何将 NSString 转换为 NSArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSString,它是一个数学表达式.我有运算符 (+,-,*,/) 和操作数 (从 0 到 9 的数字,整数,小数等).我想把这个 NSString 转换成 NSArray.例如,如果我的 NSString 是7.9999-1.234*-9.21".我希望 NSArray 具有相同顺序的元素 7.9999,-,1.234,*,-,9.21 .我怎样才能做到这一点?

I have an NSString which is a mathematical expression. I have operators (+,-,*,/) and operands (digits from 0 to 9,integers,decimals etc). I want to convert this NSString into NSArray. For example if my NSString is "7.9999-1.234*-9.21". I want NSArray having elements 7.9999,-,1.234,*,-,9.21 in the same order. How can I accomplish this?

我试过一个代码.不过,它在所有情况下都不起作用.这是:

I have tried a code. It dosent work in all scenarios though. Here It is:

代码:

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转换得到的数组.当我执行此代码时,我在控制台上得到以下信息:

Here str is the string to be converted. My array is the array obtained by converting the string str. When I execute this code I get the following on console:

 7.9999
 -
 1.234
 *
 <null>
 -

推荐答案

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

You should use NSScanner, scanning up to your operator characters, then when you find one, save the scanned string and then save the operator into the array and skip the operator (setScanLocation:). Continue doing this till you get to the end of the string (in a loop, one iteration for each operator).

这篇关于如何将 NSString 转换为 NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆