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

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 the painting|drawing example), the value stays intact instead of being split into extra array elements.
  • Validation before access: Checking keyValueParts.Length >= 2 guarantees 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 is name | Bob instead of name|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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:55:06