0

我总是让数组索引越界?

我尝试将 mymatches.Count 更改为 +1 和 -1 但它仍然超出范围。

为什么?

   public string[] readAllScripts()
    {
        string[] scripts = txt_script.Lines;

        int arraysize = scripts.Length;
        int x = 0;
        int y = 0;
        MessageBox.Show(arraysize.ToString());

        //string pattern = "[a-zA-Z]*";
        string[][] scriptarray = new string[arraysize][];

        for (int i = 0; i < scripts.Length; i++)
        {

            MatchCollection mymatches = Regex.Matches(scripts[i], "[a-zA-Z]*");

            scriptarray[i] = new string[mymatches.Count];

            foreach (Match thematch in mymatches)
            {
                scriptarray[x][y] = thematch.Value;
                y++;
            }
            x++;
        }



        return scripts;
    }
4

4 回答 4

5

看起来您需要在循环中重新初始化 y :

public string[] readAllScripts() 
{ 
    string[] scripts = txt_script.Lines; 

    int arraysize = scripts.Length; 
    int x = 0; 

    MessageBox.Show(arraysize.ToString()); 

    //string pattern = "[a-zA-Z]*"; 
    string[][] scriptarray = new string[arraysize][]; 

    for (int i = 0; i < scripts.Length; i++) 
    { 

        MatchCollection mymatches = Regex.Matches(scripts[i], "[a-zA-Z]*"); 

        scriptarray[i] = new string[mymatches.Count]; 

        int y = 0; 
        foreach (Match thematch in mymatches) 
        { 
            scriptarray[x][y] = thematch.Value; 
            y++; 
        } 
        x++; 
    } 

    return scripts; 
} 
于 2012-07-23T21:26:43.690 回答
4
        scriptarray[i] = new string[mymatches.Count];
        y = 0;   // add this
        foreach (Match thematch in mymatches)
        {
            scriptarray[x][y] = thematch.Value;
            y++;
        }

正如您所看到的,您可能已经使用了 a for (int y = 0; y < mymatches.Count; y++),并且通常它有助于使声明(如 of int y)尽可能地保持本地化。

于 2012-07-23T21:26:20.680 回答
3

摆脱所有与 linq 的索引混淆:

string[][] scriptarray = txt_script
  .Lines
  .Select(
     line =>
      Regex
        .Matches(line, "[a-zA-Z]*")
        .Cast<Match>()
        .Select(m => m.Value)
        .ToArray())
  .ToArray()
于 2012-07-23T21:54:17.347 回答
1

您需要将 y 重置为零

这边走

foreach (Match thematch in mymatches)
{
   scriptarray[x][y] = thematch.Value;
   y++;
}

y = 0;
x++;
于 2012-07-23T21:28:02.843 回答