NSString:componentsSeparatedByCharactersInSet包含

时间:2014-09-14 17:49:44

标签: objective-c tokenize shunting-yard nscharacterset

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

tokens返回:

  

[@" 4",@" 23",@" 54",@" 543",@" 23& #34;]

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

我需要什么:

  

[@" 4",@" +",@" 23",@" - ",@&#34 ; 54",@" /",@" 543",@" *",@" 23"]

1 个答案:

答案 0 :(得分:0)

如果你想使用regEx,你可以在运算符之前和之后插入一个空格,然后用空格分割字符串。

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:@" "];