简体   繁体   中英

trying to int.parse multi array string

Im doing this:

string[,] string1 = {{"one", "0"},{"Two", "5"},{"Three","1"}};
int b = 0;

for(int i = 0; i <= string1.Length; i++)
{
     b = int.Parse(string1[i, 1]); // Error occurs here
}

Im getting an error saying that "index extent the limits of the array" (or something like that, the error is in danish).

There are two problems:

  • string1.Length will return 6, as that's the total length of the array
  • You're using <= for the comparison, so it would actually try to iterate 7 times.

Your for loop should be:

for (int i = 0; i < string1.GetLength(0); i++)

The call to GetLength(0) here will return 3, as the size of the "first" dimension. A call to GetLength(1) return 2, as the second dimension is of size 2. (You don't need that though, as you're basically hard-coding the knowledge that you want the second "column" of each "row".)

See the docs for Array.GetLength() for more details.

Your array bounds are incorrect in the loop:

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

should read:

for(int i = 0; i < string1.GetLength(0); i++) 

Two things were wrong: <= versus < meant you were going one item too far, and .Length returns the total length of the array (6) versus GetLength(0) which returns the length of the first dimension (3).

You already have the right answer, I'll update mine just to correct it. To right iteration should be

        for (int i = 0; i < string1.GetLength(0); i++)
        {
            b = int.Parse(string1[i, 1]);
        }

Because i stands for the length of the first dimension, and the fixed 1 will return the number, that is the second element.

I'm sorry for the wrong answer I gave first.

change to

for(int i = 0; i <= string1.GetLength(0); i++) 
{ 
b = Int32.Parse(string1[i][0]);
}

Your code is refering at index 1 rather than 0 which causes exception known as Array out of bound

i <= string1.Length更改为i < string1.Length

Try this:

for(int i = 0; i < string1.GetLength(0) ; i++)
{
     b = int.parse(string1[i, 0]); // Error occurs here
}

Array.GetLength Method

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

另外值得一提的是int.Parse可能抛出一个FormatException ,考虑int.TryParse

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