多类型多组合输入解析功能实现求助:支持同时处理整数与多字符串输入
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:
- You’re looping through lines from
ProgramWindow.Text, but inside the loop you’re always parsingCommandLine.Textinstead of the current line. That means you’ll run the same command multiple times instead of processing each line individually. - 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.Textinstead of reusingCommandLine.Textevery time. - Mixed parameter support: The code automatically detects if a parameter is an integer or string, and handles key-value pairs like
speed=10ortarget=enemy. - Error resilience: Uses
int.TryParseinstead ofint.Parseso 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
Commandsmethod: If you want to use string parameters or more than two integers, modifyCommandsto acceptList<int>andList<string>instead of just X/Y. - Quoted string support: If you need to handle multi-word strings (like
"hello world"), replace theSplit(' ')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
Commandclass to hold the command name and lists of int/string parameters for cleaner code.
内容的提问来源于stack exchange,提问作者IronMike
相关产品推荐
相关产品推荐

