简体   繁体   中英

Array out of bounds?

I keep gettting array index out of bounds?

Iv'e tried with changing mymatches.Count to +1 and -1 But it's still out of bounds.

Why?

   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;
    }

Looks like you need to reinitialize y in the loop:

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++;
        }

As you can see you might as well have used a for (int y = 0; y < mymatches.Count; y++) and in general it helps to keep declarations (like that of int y ) as local as possible.

Get rid of all index confusion with linq:

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

you need to reset y to zero

this way

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

y = 0;
x++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM