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

tokens returns:

[@"4", @"23", @"54", @"543", @"23"]

I am trying to implement Shunting Yard in Objective-C. How can I tokenize the infix string with the operator set without removing the operator set itself from the tokenization?

What I need:

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

Daniel Node.js
  • 6,734
  • 9
  • 35
  • 57

1 Answers1

0

If you'd like to use regEx, you could insert a space before and after the operators and then split the string by spaces.

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:@" "];
BCBlanka
  • 485
  • 3
  • 7