簡體   English   中英

數組越界?

[英]Array out of bounds?

我讓gettting數組索引超出范圍嗎?

我嘗試將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;
    }

看起來您需要在循環中重新初始化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; 
} 
        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 )盡可能地保持局部。

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

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

您需要將y重置為零

這條路

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

y = 0;
x++;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM