Cocoa / Objective-C中的简单字符串解析:将命令行解析为命令和参数 [英] Simple string parsing in Cocoa / Objective-C: parsing a command line into command and arguments
问题描述
下面是一段代码,用于接受代表命令行的字符串(NSString或NSAttributedString) input
,并将其解析为两个字符串,命令 cmd
和参数 args
:
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.
添加:解决方案也应该是鲁棒的初始空格。此外,我最初有一个输入字符串 input
和 inStr
。对不起,这个混乱。
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.
添加:我相信上述代码是正确的,答案到目前为止不是args不应该有任何初始空格。 / 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.
推荐答案
NSString *cmd;
NSScanner *scanner = [NSScanner scannerWithString:[inStr string]];
[scanner scanUpToCharactersFromSet:[NSCharacterSet
whitespaceAndNewlineCharacterSet]
intoString:&cmd];
NSString *args = [[scanner string] substringFromIndex:[scanner scanLocation]];
您的autoreleases可以,但首先分配字符串是不必要的,因为NSScanner返回一个新的字符串参考。由于NSScanner的charactersToBeSkipped在默认情况下包含空格,因此它不应该被初始空格占用。
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.
这篇关于Cocoa / Objective-C中的简单字符串解析:将命令行解析为命令和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!