How do I use NSScanner to parse a tab-delimited string in Cocoa?
I have a web service that returns tab delimited data (see example below).
I need to parse this into an array or similar so that I can create a navigation view.
I was able to execute a web request and parse an XML file, but my Objective-C knowledge is not great.
433 Eat
502 Not Fussed
442 British
443 Chinese
444 Dim Sum
445 Fish
446 French
447 Gastropubs
449 Indian
451 Italian
452 Japanese
453 Middle Eastern
454 Pan-Asian
455 Pizza
456 Spanish
457 Tapas
458 Thai
459 Vegetarian
434 Drink
501 Not Fussed
460 Bars
461 Pubs
source to share
You are on the right track with NSScanner. You will need at least two scanners: one to scan lines from the entire input line, and one scanner for each line. Set the whole input scanner to only skip spaces (not newlines), then:
- Scan one line (original line to end of line).
- Build a scanner and scan tabs from string.
- Count the browsed tabs. This is your indentation level.
- The rest of the line is the record number and name. You can scan the line up to a space to separate the number and name, or leave them together, whichever you want.
- Go back to step 1.
For specific method names, see the NSScanner class reference and the NSCharacterSet class reference .
source to share
I'm not sure if I understand your format exactly (this is a bit strange to me), but the easiest way to do this is with - (NSArray *)componentsSeparatedByString:(NSString *)separator
, which is a method of the NSString class ... example:
NSArray *components = [myString componentsSeperatedByString:@"\t"];
This returns NSArray
of NSStrings
, one for each tab-delimited field. If newline separators are important, you can use - (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
(also on NSString
) to separate using more than one type of separator.
source to share
I had a feeling that a flatter list was needed. If you need a multidimensional structure, you can do something like this:
NSArray *lines = [data componentsSeparatedByString:@"\n"];
for (NSString *line in lines) {
NSArray *fields = [line componentsSeparatedByString:@"\t"];
// Do something here with each two-element array, such as add to an NSDictionary or to an NSArray (to make a multidimensional array.)
}
source to share