Search code examples
objective-csplitnsstringnsarrayexpression

Objective C - Split string on any non alpha characters



I am using a math parser to evaluate and calculate formulas, these could contain any variables from an array of hundreds, what I need to be able to do is get an array of the variable names from the formula string (which will only be made up of alpha characters) so that I can then find the appropriate values before parsing the expression.

I have a formula like the following:

PARAMONE*(1+((PARAMTWO-1)/30))^(PARAMTHREE+1)

what I would like to have form this is an NSArray [PARAMONE, PARAMTWO, PARAMTHREE] but can't figure out how to remove and split the formulas to achieve this.

Any help is greatly appreciated.

Thanks


Solution

  • This will do as you have described

    NSString *formula = @"PARAMONE*(1+((PARAMTWO-1)/30))^(PARAMTHREE+1)";
    
    //  A character set containing everything but the letters
    NSCharacterSet *splitCharacterSet = [[NSCharacterSet letterCharacterSet] invertedSet];
    
    NSMutableArray *words = [[formula componentsSeparatedByCharactersInSet:splitCharacterSet] mutableCopy];
    
    //  Remove any empty strings as a result of the split
    [words removeObject:@""];
    
    NSLog(@"%@", words);