binaryZomby
binaryZomby

Reputation: 21

Parse a string with several separators

I'm trying to implement a calculator to become a bit more familiar with Objective-C. I have a string entered by the user which could be something like "41*92". What would be a good way to parse the string to add the 2 numbers to an array? Something like componentsJoinedByString: but with four different separators at this stage (+,-,*,/)?

Upvotes: 0

Views: 70

Answers (2)

DarkDust
DarkDust

Reputation: 92442

You can split the string like @Sean said, but if you want to actually parse an input like 41*92, the way to do it is usually to use NSScanner. See Apple's String Programming Guide: Scanners or search for NSScanner tutorial, there are plenty.

(You can also "cheat" using NSExpression if you'd like to evaluate math expressions, but I guess that's not what you want.)

Upvotes: 1

Sean
Sean

Reputation: 1534

You can use componentsSeparatedByCharactersInSet:

NSArray *arr = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"+-*/"]];

Upvotes: 3

Related Questions