AKST
AKST

Reputation: 191

How do i parse an NSString to get the words and operators separately in 2 different arrays

I have a String

NSString *formula = @"base+unit1-unit2*unit3/unit4";

I am able to get all the words in an array using code :

NSArray *myWords = [formula componentsSeparatedByCharactersInSet:
                            [NSCharacterSet characterSetWithCharactersInString:@"+-*/"]];

//myWords = {base , unit1,unit2,unit3,unit4}

but i am facing problem in getting all the operators in an array like this myOperators = {+,-,*,/} Please advice thanks

Upvotes: 0

Views: 149

Answers (4)

JuJoDi
JuJoDi

Reputation: 14975

You can create a character set containing all characters except your operators using invertedSet

NSCharacterSet *operatorCharacters = [NSCharacterSet characterSetWithCharactersInString:@"+-/*"];
NSCharacterSet *otherCharacters = [operatorCharacters invertedSet];    

NSArray *operatorComponents = [formula componentsSeparatedByCharactersInSet:
                            otherCharacters];

You'll then want to remove any empty strings from a mutable copy of the array

NSMutableArray *mutableOperators = [operatorComponents mutableCopy];
[mutableOperators removeObject:@""];

Upvotes: 1

Alexander Ney
Alexander Ney

Reputation: 781

You could use NSRegularExpression to accomplish that. A quick solution could be:

NSString *formula = @"base+unit1-unit2*unit3/unit4";
NSRegularExpression *testExpression = [NSRegularExpression regularExpressionWithPattern:@"[*-/]"
                                                                                         options:NSRegularExpressionCaseInsensitive error:nil];

[testExpression enumerateMatchesInString:formula
                                 options:0
                                   range:NSMakeRange(0, formula.length)
                              usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                              NSLog(@"%@", [formula substringWithRange:result.range]); 
}];

you can build a mutable Array within that block with all the operators found according to the regular expression.

The regular expression ist just a quick example - you could create something more fancy than that :)

Upvotes: 1

Sam Jarman
Sam Jarman

Reputation: 7377

Would something like this work? (psudocode):

for character in string:

    if character is one of +, -, /, *:

        add to array

return array

Upvotes: 0

Wain
Wain

Reputation: 119041

Use NSScanner to walk through the string extracting all of the parts you need (see scanCharactersFromSet:intoString: and scanUpToCharactersFromSet:intoString:).

Upvotes: 4

Related Questions