C#多分隔符字符串转数组再转字典时遇数组越界错误求助
Fixing "Index was outside the bounds of the array" When Parsing Multi-Delimiter Strings to Dictionary
Hey there! Let's break down why you're hitting that frustrating array out-of-bounds error and fix it step by step.
Common Causes of the Error
That error almost always pops up when one of your "rows" (after splitting by ~) doesn't match the key|value format you expect. Here are the top culprits:
- A row is empty (like if your input starts/ends with
~, or has two~in a row) - A row has no
|character at all (so splitting by|gives an array with only one element) - You're splitting by
|without limiting the number of parts, and some values contain|(though this usually causes unexpected values rather than out-of-bounds, but still worth checking)
Step-by-Step Solution
The fix involves validating each row before trying to access split parts, and handling edge cases gracefully. Here's a practical code example (using C# since it's common for dictionary operations) that addresses all these issues:
// Example input (note the empty/invalid rows to simulate your scenario) string input = "name|Alice~age|28~~invalidRow~hobby|painting|drawing"; var keyValueDict = new Dictionary<string, string>(); // Split by ~, then filter out empty or whitespace-only rows var rows = input.Split('~') .Where(row => !string.IsNullOrWhiteSpace(row)); foreach (var row in rows) { // Split each row into MAX 2 parts using | — this preserves | characters in the value var keyValueParts = row.Split(new[] {'|'}, 2); // Only proceed if we have at least a key and a value if (keyValueParts.Length >= 2) { string key = keyValueParts[0].Trim(); string value = keyValueParts[1].Trim(); // Skip empty keys to avoid invalid dictionary entries if (!string.IsNullOrWhiteSpace(key)) { // Use [] to overwrite existing keys, or .Add() if you want to throw on duplicates keyValueDict[key] = value; } } // Optional: Add logging here to track skipped rows for debugging // else { Console.WriteLine($"Skipping invalid row: '{row}'"); } }
Key Fixes in This Code
- Filtering empty rows: The
Where(row => !string.IsNullOrWhiteSpace(row))line removes any blank entries from the initial split, which eliminates one major source of the error. - Limiting split parts: Using
Split(new[] {'|'}, 2)ensures that even if your value contains|characters (like thepainting|drawingexample), the value stays intact instead of being split into extra array elements. - Validation before access: Checking
keyValueParts.Length >= 2guarantees you don't try to access an index that doesn't exist. - Trimming whitespace:
Trim()cleans up any accidental spaces around keys or values (e.g., if a row isname | Bobinstead ofname|Bob).
For Other Languages
If you're using Java, the logic is nearly identical:
- Split the input with
input.split("~") - Filter out empty strings with
Arrays.stream(rows).filter(row -> !row.isBlank()) - Split each row with
row.split("\\|", 2)(note the escaped|since it's a regex special character) - Check if the resulting array has at least 2 elements before adding to the map.
内容的提问来源于stack exchange,提问作者jbeckom
相关产品推荐
相关产品推荐

