tamaramaria tamaramaria - 16 days ago 6
C# Question

convert 2D string array into 2D int array

I want to replace String[,] 2D array

public static readonly string[,] first =
{
{"2", " ", " ", " ", "1"},
{"2", " ", "4", "3", " "},
{" ", "2", " ", "1", " "},
{" ", "1", " ", "3", " "},
{"1", " ", " ", " ", " "}
};


into int[,] array

int X=-1;
public static readonly int[,] second =
{
{2, X, X, X, 1},
{2, X, 4, 3, X},
{X, 2, X, 1, X},
{X, 1, X, 3, X},
{1, X, X, X, X}
};


Is it possible to convert a string[,] array to an int[,] array? How can I convert the string[,] into int[,] ? Thank you

Jim Jim
Answer
public static readonly string[,] first =
{
     {"2", " ", " ", " ", "1"},
     {"2", " ", "4", "3", " "},
     {" ", "2", " ", "1", " "},
     {" ", "1", " ", "3", " "},
     {"1", " ", " ", " ", " "}
};

convert (note that when the string = " ", I'm putting a 0 instead):

int[,] second = new int[first.GetLength(0), first.GetLength(1)];

for (int j = 0; j < first.GetLength(0); j++)    
{
    for (int i = 0; i < first.GetLength(1); i++)
    {
        int number;
        bool ok = int.TryParse(first[j, i], out number);
        if (ok)
        {
            second[j, i] = number;
        }
        else
        {
            second[j, i] = 0;
        }
    }
}