1
NSString *infix = @"4+23-54/543*23";
NSCharacterSet *operatorSet = [NSCharacterSet characterSetWithCharactersInString:@"+-*/"];
NSArray *tokens = [infix componentsSeparatedByCharactersInSet:operatorSet];

tokens返回:

[@“4”,@“23”,@“54”,@“543”,@“23”]

我正在尝试在 Objective-C 中实现 Shutting Yard。如何使用运算符集标记中缀字符串而不从标记化中删除运算符集本身?

我需要的:

[@"4"、@"+"、@"23"、@"-"、@"54"、@"/"、@"543"、@"*"、@"23"]

4

1 回答 1

0

如果你想使用正则表达式,你可以在运算符前后插入一个空格,然后用空格分割字符串。

NSString *infix = @"4+23-54/543*23";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"([+,*,/,-])" options:0 error:NULL];
NSString *newString = [regexp stringByReplacingMatchesInString:infix options:0 range:NSMakeRange(0, infix.length) withTemplate:@" $1 $2"];
NSArray *tokens = [newString componentsSeparatedByString:@" "];
于 2014-09-15T09:16:12.157 回答