简体   繁体   English

解析命令行参数字符串

[英]Parsing command line parameters string

This will seem a strange question so I will explain it as simply as possible. 这似乎是一个奇怪的问题,所以我将尽可能简单地解释它。 I am making an app like CMD in C# and I need to have commands like 'ping'. 我正在用C#制作像CMD这样的应用程序,我需要使用诸如“ ping”之类的命令。 I have a switch statement that checks the command entered and executes it. 我有一个switch语句,用于检查输入的命令并执行它。 This is: 这是:

switch (CommandName)
{
    case "intro":
        {
            Console.WriteLine("intro");
            CommandListen();
        }
        break;

    case "clear":
        {
            CommandFolder.CmdClear cmd = new CommandFolder.CmdClear();
            cmd.Execute();
            CommandListen();
        }
        break;

    case "ping":
        {
            CommandFolder.CmdPing cmd = new CommandFolder.CmdPing();
            cmd.Execute(CommandName);
            CommandListen();
        }
        break;

    case "exit":
        {
            CommandFolder.CmdExit cmd = new CommandFolder.CmdExit();
            cmd.Execute();
        }
        break;

    default:
        CommandListen();
        break;
}

I have no idea how to get it to work with parameters for a command, ie ping [ip/url] [extra]. 我不知道如何使它与命令的参数一起使用,即ping [ip / url] [extra]。 If I enter 'ping' it works and executes the command, but if I enter 'ping www.google.com' it comes up with my unrecognized command error. 如果输入“ ping”,它将起作用并执行命令,但是,如果输入“ ping www.google.com”,它将出现我无法识别的命令错误。 I need a way to check the first part of the command, and then pass the parameters through. 我需要一种方法来检查命令的第一部分,然后通过传递参数。

I apologize if this is vague, I just didn't know how to word it. 如果这含糊,我深表歉意,我只是不知道该怎么说。

You need to define a syntax and write a parser for that. 您需要定义语法并为此编写解析器。 As @Lasse and @Dan suggested in the comments, it can be as simple as "a command and its parameters are separated by one space", which will make a naive implementation of the parsing code look like this: 正如@Lasse和@​​Dan在注释中所建议的那样,它可以很简单,例如“一个命令及其参数由一个空格分隔”,这将使解析代码的幼稚实现看起来像这样:

string commandParts = CommandName.Split(" ");
string commandName = commandParts[0];
var arguments = commandParts.Skip(1).ToList();

var command = new SomeCommand(arguments);

This code splits the input on space (" "), takes the first result as the command and the optional remainder as arguments (no arguments entered will become an empty arguments list). 此代码在空格(“”)上分割输入,将第一个结果作为命令,并将可选的其余部分作为参数(没有输入的参数将成为空arguments列表)。

You'll of course need to add code for error handling for when no command is entered, or adjust the split code if you want to support multiple spaces being entered. 当然,您需要为没有输入命令时的错误处理添加代码,或者如果您想支持输入多个空格,请调整拆分代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM