数组越界?

时间:2012-07-23 21:23:37

标签: c# arrays

我一直在使数组索引超出范围?我尝试将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 个答案:

答案 0 :(得分: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; 
} 

答案 1 :(得分:4)

        scriptarray[i] = new string[mymatches.Count];
        y = 0;   // add this
        foreach (Match thematch in mymatches)
        {
            scriptarray[x][y] = thematch.Value;
            y++;
        }

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

答案 2 :(得分:3)

使用linq消除所有索引混淆:

string[][] scriptarray = txt_script
  .Lines
  .Select(
     line =>
      Regex
        .Matches(line, "[a-zA-Z]*")
        .Cast<Match>()
        .Select(m => m.Value)
        .ToArray())
  .ToArray()

答案 3 :(得分:1)

您需要将y重置为零

这样

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

y = 0;
x++;