我怎样才能以编程方式拆分一个变量?

时间:2013-05-10 21:55:14

标签: ios variables split

我有一个类似的nsstring:

Variable1 = x;\n    Variable2 = y;\n    variable3 = z;\n    variable4 = t

提出一个明确的问题我正在显示我的nsstring的nslog:

NSLog(@"%@",myNsString);

在NSLOG:

    Variable1 = x
    Variable2 = y
    variable3 = z
    variable4 = t

我希望将它们分成不同的变量。

1 个答案:

答案 0 :(得分:2)

所以听起来你想在单独的字符串中使用x,y,z和t值?你有一个巨大的字符串吗?如果您需要帮助,请尝试更清楚,但这应该让您开始朝着正确的方向前进:

NSString *yourNSString = @"Variable1 = x;\n    Variable2 = y;\n    variable3 = z;\n    variable4 = t";

NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"=;"];
NSArray *splitter = [yourNSString componentsSeparatedByCharactersInSet:set];
NSString *x;
NSString *y;
NSString *z;
NSString *t;

for(int i = 0; i<splitter.count ; i++)
{
    if(i==1)
    {
        x = [[splitter objectAtIndex:i]stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    else if(i==3)
    {
        y = [[splitter objectAtIndex:i]stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    else if(i==5)
    {
        z = [[splitter objectAtIndex:i]stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
    else if(i==7)
    {
        t = [[splitter objectAtIndex:i]stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}