How do i parse an NSString to get the words and op

2019-08-30 08:13发布

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

4条回答
放荡不羁爱自由
2楼-- · 2019-08-30 08:42

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

查看更多
虎瘦雄心在
3楼-- · 2019-08-30 08:48

Would something like this work? (psudocode):

for character in string:

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

        add to array

return array
查看更多
放荡不羁爱自由
4楼-- · 2019-08-30 08:50

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 :)

查看更多
戒情不戒烟
5楼-- · 2019-08-30 08:59

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:@""];
查看更多
登录 后发表回答