1

I have a string containing numbers as a 2D matrix. I'm trying to use Split function to split the contents of a string into an array. So, when I do:

String[] subStrs = new String[20];
subStrs = str.Split('\n'); 

The code above works fine. However, when I try to create a 2D array and try to populate sub-arrays using the same way:

String[,] numbers = new String[20,20];
for (int i = 0; i < subStrs.Length; i++ )
{
    numbers[i] = subStrs[i].Split(' '); //Error
}

I get the following compiler error:

Wrong number of indices inside []; expected 2.

If 2D array is really an array of arrays, then why is the statement numbers[i] = subStrs[i].Split(' '); illegal?

PS : I do know that I can use a nested loop instead to populate numbers. I'm just curious why can't I use the above method?

9
  • 1
    There's no point in creating arrays that you're going to immediately overwrite with a new array. Only create a new array when you actually intend to access the values of that array. Commented Mar 30, 2015 at 19:03
  • string[,] and string[][] are two different things. Split returns a string[] so it can be added to an array of arrays (i.e. string[][]), but not a 2D array string[,] without some more work (i.e. you'd need an inner loop to assign values to the correct cells in a string[,]) Commented Mar 30, 2015 at 19:03
  • @Servy I'm sorry, I didn't understand your comment. Could you please elaborate that? Commented Mar 30, 2015 at 19:05
  • @Dumbledore You're creating an array and then immediately throwing it away and assigning a new array to that variable. That's pointless. Just don't create a new array if you're just going to throw it away and assign a new array to that variable without using it. Commented Mar 30, 2015 at 19:06
  • @Servy Are you talking about subStrs? Commented Mar 30, 2015 at 19:08

1 Answer 1

8

If 2D array is really an array of arrays

It's not. A 2D array is just that, a 2D array.

An array of arrays is an array of arrays:

string[][]

If you have an array of arrays, then the item at each index of the outer array is another array. If you have a 2D array then both dimensions are needed to get at a value, which is itself the value of the array, not another dimension.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.