Convert 2D string array into 2D int array (Multidimensional Arrays)

戏子无情 提交于 2020-01-15 09:29:09

问题


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.


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



回答2:


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



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/40708656/convert-2d-string-array-into-2d-int-array-multidimensional-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!