You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多类型多组合输入解析功能实现求助:支持同时处理整数与多字符串输入

Flexible Input Parsing for Mixed String/Integer Commands

Alright, let's fix this up for you. Looking at your code, I see two critical issues holding you back:

  1. You’re looping through lines from ProgramWindow.Text, but inside the loop you’re always parsing CommandLine.Text instead of the current line. That means you’ll run the same command multiple times instead of processing each line individually.
  2. Your parsing logic only handles one narrow format (a command followed by comma-separated integers), which doesn’t account for mixed string/int parameters or key-value pairs like string=int.

Here’s a revised version of your code that handles all the input combinations you listed (string = int, string + int, string int, string int int, etc.):

private void button1_Click(object sender, EventArgs e) {
    // Split input into lines, clean up empty/whitespace-only lines
    string[] lines = ProgramWindow.Text.Split('\n')
        .Select(line => line.Trim())
        .Where(line => !string.IsNullOrEmpty(line))
        .ToArray();

    foreach (string line in lines) {
        // Split the current line into tokens, ignore empty entries
        string[] tokens = line.ToLower().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        if (tokens.Length == 0) continue;

        string command = tokens[0];
        List<int> intParameters = new List<int>();
        List<string> stringParameters = new List<string>();

        for (int i = 1; i < tokens.Length; i++) {
            string token = tokens[i];

            // Handle key-value pairs (e.g., "move=5" or "name=player1")
            if (token.Contains('=')) {
                string[] keyValue = token.Split('=', 2); // Split only once to preserve values with =
                if (keyValue.Length != 2) continue;

                string value = keyValue[1].Trim();
                if (int.TryParse(value, out int intVal)) {
                    intParameters.Add(intVal);
                } else {
                    stringParameters.Add(value);
                }
            }
            // Handle standalone parameters (e.g., "5" or "north")
            else {
                if (int.TryParse(token, out int intVal)) {
                    intParameters.Add(intVal);
                } else {
                    stringParameters.Add(token);
                }
            }
        }

        // Extract X/Y like your original code, but with fallbacks
        int X = intParameters.Count >= 1 ? intParameters[0] : 0;
        int Y = intParameters.Count >= 2 ? intParameters[1] : 0;

        // Example output to verify parsing
        Console.WriteLine($"Command: {command}, X: {X}, Y: {Y}, String Params: {string.Join(", ", stringParameters)}");
        
        // If you want to pass all parameters to your Commands method, you might need to update it
        // For now, we'll use your original method signature
        Commands(command, X, Y);
        Refresh();
    }
}

Key Improvements:

  • Line-by-line processing: Now we actually parse each line from ProgramWindow.Text instead of reusing CommandLine.Text every time.
  • Mixed parameter support: The code automatically detects if a parameter is an integer or string, and handles key-value pairs like speed=10 or target=enemy.
  • Error resilience: Uses int.TryParse instead of int.Parse so invalid number inputs won’t crash your app (they’ll just be treated as strings).
  • Cleaner input handling: Trims whitespace and skips empty lines to avoid unnecessary processing.

Next Steps to Enhance Further:

  • Update the Commands method: If you want to use string parameters or more than two integers, modify Commands to accept List<int> and List<string> instead of just X/Y.
  • Quoted string support: If you need to handle multi-word strings (like "hello world"), replace the Split(' ') with a regex that respects quotes, e.g.:
    var tokens = Regex.Matches(line, @"(""[^""]*""|\S+)")
                      .Cast<Match>()
                      .Select(m => m.Value.Trim('"'))
                      .ToArray();
    
  • Formal parameter structure: Create a small Command class to hold the command name and lists of int/string parameters for cleaner code.

内容的提问来源于stack exchange,提问作者IronMike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 08:57:26