1

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? If yes, how can I convert the string[,] into int[,]? Thank you.

Jim
  • 2,974
  • 2
  • 19
  • 29
tamaramaria
  • 173
  • 1
  • 4
  • 17
  • I have tried to solve this with a loop, but I couldn't do it because the X should be the empty String `""` – tamaramaria Nov 20 '16 at 19:54
  • I don't understand what you're trying to do, then. If `X` isn't an `int`, then you can't put it in an `int` array. – user94559 Nov 20 '16 at 20:03

4 Answers4

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


int[,] second = new int[first.GetLength(0), first.GetLength(1)];
int x = -1;
for (int i = 0; i < first.GetLength(0); i++)
{
    for (int j = 0; j < first.GetLength(1); j++)
    {
        second[i, j] = string.IsNullOrWhiteSpace(first[i, j]) ? x : Convert.ToInt32(first[i, j]);
    }
}
Peroxy
  • 646
  • 8
  • 18
1

Live example: Ideone

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;
        }
    }
}
Jim
  • 2,974
  • 2
  • 19
  • 29
1

Assuming X = -1:

private static int[,] ConvertToIntArray(string[,] strArr)
{
    int rowCount = strArr.GetLength(dimension: 0);
    int colCount = strArr.GetLength(dimension: 1);

    int[,] result = new int[rowCount, colCount];
    for (int r = 0; r < rowCount; r++)
    {
        for (int c = 0; c < colCount; c++)
        {
            int value;
            result[r, c] = int.TryParse(strArr[r, c], out value) ? value : -1;
        }
    }
    return result;
}
andrasp
  • 168
  • 1
  • 1
  • 7
-1

Use the loop you are using and replace the empty strings by null values, and if you're going to use this array just check if the value is not null.