title: Simple string parsing in Cocoa / Objective-C: parsing a command line into command and arguments
body: <p>Here's a piece of code to take a string (either NSString or NSAttributedString) <code>input</code> that represents a command line and parse it into two strings, the command <code>cmd</code> and the arguments <code>args</code>:</p>
  
  <pre><code>NSString* cmd = [[input mutableCopy] autorelease];
  NSString* args = [[input mutableCopy] autorelease];
  NSScanner* scanner = [NSScanner scannerWithString:[input string]];
  [scanner scanUpToCharactersFromSet:[NSCharacterSet 
                                      whitespaceAndNewlineCharacterSet] 
                          intoString:&amp;cmd];
  if (![scanner scanUpToString:@"magicstring666" intoString:&amp;args]) args = @"";
  </code></pre>
  
  <p>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.</p>
  
  <p>ADDED: The solution should also be robust to initial whitespace.  Also, I originally had the input string called both <code>input</code> and <code>inStr</code>.  Sorry for that confusion.</p>
  
  <p>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.</p>