danielbeard
danielbeard

Reputation: 9149

Splitting an input string with objective-c

I am using ASIHTTPREQUEST in an iPhone project to get some data that looks something like this (as an NSString):

name:daniel, age:22, occupation:runner, name:greg, age:32, occupation:plumber

and I want to parse these into dictionaries or arrays so that I can get all names, or all occupations etc.

How can I do this in objective-c?

Thanks

Upvotes: 0

Views: 242

Answers (1)

Caleb
Caleb

Reputation: 124997

One way is to use NSString's -componentsSeparatedByString: method with a separator string of @", " to break the string up into separate substrings, one for each key/value pair. Then you can use it again with a separator of @":" to break each substring into a key and a value, and insert these into a dictionary.

Another way is to use NSScanner to scan through your input string, taking the keys and values sequentially.

Upvotes: 1

Related Questions