首页 > 解决方案 > 某些文本输入会导致数组超出范围

问题描述

我想解析 CommandLine可以有两种格式:

  1. command 123- 带1参数的命令 ( 123)
  2. command 123,456- 带2参数的命令(123456

这里command- 命令的名称,后跟空格' '和参数:123123,456以逗号分隔,

我试图用下面的代码来实现这个目标:

        for (int i = 0; i <= CommandLine.TextLength; i++)
        {
            String[] CommandLineText = CommandLine.Text.Split(' ');
            String Commands = CommandLine.Text.ToLower().Trim();
            String Command = CommandLineText[0];
            String Values = CommandLineText[1];
            String[] Parameters = Values.Split(',');
            int X = Int32.Parse(Parameters[0]);
            int Y = Int32.Parse(Parameters[1]);
        }

我遇到的问题是,当命令采用只有1数字的第一种格式时,第二个参数变得out of bounds

标签: c#parsing

解决方案


假设您有一些命令需要 1 个参数,而其他命令需要 2 个......

您需要采取一些小步骤,以便您可以看到解析在什么时候出现故障。这也将允许您告诉用户错误的确切位置:

private void button1_Click(object sender, EventArgs e)
{
    String rawCommand = CommandLine.Text.ToLower().Trim();
    if (rawCommand.Length > 0)
    {
        String[] parts = rawCommand.Split(' ');
        if (parts.Length >= 2)
        {
            String command = parts[0];
            String[] args = parts[1].Split(',');
            if (args.Length == 1)
            {
                String arg1 = args[0];
                int X;
                if (Int32.TryParse(arg1, out X))
                {
                    // ... do something in here with "command" and "X" ...
                    Console.WriteLine("Command: " + command);
                    Console.WriteLine("X: " + X);
                }
                else
                {
                    MessageBox.Show("Invalid X Argument!");
                }
            }
            else if(args.Length >= 2)
            {
                String arg1 = args[0];
                String arg2 = args[1];
                int X, Y;
                if (Int32.TryParse(arg1, out X) && Int32.TryParse(arg2, out Y))
                {
                    // ... do something in here with "command" and "X" and "Y" ...
                    Console.WriteLine("Command: " + command);
                    Console.WriteLine("X: " + X);
                    Console.WriteLine("Y: " + Y);
                }
                else
                {
                    MessageBox.Show("Invalid X and/or Y Argument!");
                }
            }
        }
        else
        {
            MessageBox.Show("Command has no Parameters!");
        }
    }
    else
    {
        MessageBox.Show("Missing Command!");
    }           
}

推荐阅读