C#: How to detect arguments typed into console application?

前端 未结 8 1398
长情又很酷
长情又很酷 2020-12-13 02:43

How would I go upon detecting input for a console application in C#?

Let\'s say for example I want the console application to start up by writing: Welcome To Food Hu

相关标签:
8条回答
  • 2020-12-13 03:09

    Paul is right, you will need to use the various String members to accomplish this task.

    MSDN

    If you are feeling really enterprise, you can look at using the String.Text.RegularExpression class to parse the text, but to start out, use the string members.

    Also try googling C# String parsing.

    0 讨论(0)
  • 2020-12-13 03:09

    Came across gsscoder/commandline. A clean Object Oriented implementation, available through NuGet.

    0 讨论(0)
  • 2020-12-13 03:20

    To skip coding basics, you might want to take a look inside Genghis project's Command line parsing sub-project by Chris Sells. It's first one in the table on linked page.

    0 讨论(0)
  • 2020-12-13 03:22

    My immediate suggestion would be something like this:

    string input = Console.ReadLine();
    if (input == "/help") { }
    else if (input.StartsWith("/food")) { }
    else { //... }
    

    Barring that, the next simplest solution involves regex. If you need something truly extensible, you might look into a lexer/parser.

    But then again, something tells me you're approaching the problem the wrong way. Maybe it would just be easier to display a menu to your user, something like this:

    Food:
    1) Tofu
    2) Tempeh
    3) Seitan
    4) Soup
    
    Choice (1-4)? [users input]
    
    Drink:
    1) Pepsi
    2) Coffee
    3) Water
    4) Tea
    5) Juice
    
    Choice (1-5)? [users input]
    

    Numbered menus might be a little easier for your users to digest.

    0 讨论(0)
  • 2020-12-13 03:29

    Use string.split to find all words separated by a space.

    input = Console.ReadLine();
    string[] commands = input.Split(' ');
    if(commands[0] == "/food")
    {
     if(commands[1] == "Pizza");
       .....
    }
    
    0 讨论(0)
  • 2020-12-13 03:32

    Look into String.Contains

    0 讨论(0)
提交回复
热议问题