Simple string parsing in Cocoa / Objective-C: parsing a command line into command and arguments
cocoa, command-line, objective-c, parsing, regex
Solution
NSString *cmd;
NSScanner *scanner = [NSScanner scannerWithString:[inStr string]];
[scanner scanUpToCharactersFromSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]
intoString:&cmd];
NSString *args = [[scanner string] substringFromIndex:[scanner scanLocation]];
Your autoreleases were OK, but allocating strings in the first place was unnecessary since NSScanner returns a new string by reference. Since NSScanner's charactersToBeSkipped include whitespace by default, it shouldn't get tripped up by initial whitespace.
Problem
Here's a piece of code to take a string (either NSString or NSAttributedString) `input` that represents a command line and parse it into two strings, the command `cmd` and the arguments `args`: ``` NSString* cmd = [[input mutableCopy] autorelease]; NSString* args = [[input mutableCopy] autorelease]; NSScanner* scanner = [NSScanner scannerWithString:[input string]]; [scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] intoString:&cmd]; if (![scanner scanUpToString:@"magicstring666" intoString:&args]) args = @""; ``` That seems to work but the magic string is a pretty absurd hack. Also, I'm not at all sure I'm doing things right with the autoreleases. ADDED: The solution should also be robust to initial whitespace. Also, I originally had the input string called both `input` and `inStr`. Sorry for that confusion. ADDED: I believe one thing the above code gets right that the answers so far don't is that args should not have any initial whitespace.