2012-07-23 78 views
0

我保持gettting数组索引超出范围?数组越界?

Iv'e尝试更改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; 
    } 
+0

你确定你是否得到正则表达式匹配? – Brian 2012-07-23 21:24:47

+0

@布莱恩 - 这里没关系。 'scriptarray [i]'可以很好地保存0个元素的数组。没有理由超越界限。 – 2012-07-23 21:32:30

回答

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; 
} 
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)地方越好。

1

你需要这样

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

y = 0; 
x++; 
3

开始使用LINQ摆脱所有指数的混乱与Y归零

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