将2D字符串数组转换为2D int数组(多维数组)

时间:2016-11-20 19:51:15

标签: c# arrays multidimensional-array type-conversion 2d

我想替换string[,] 2D数组

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

进入int[,]数组

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

是否可以将string[,]数组转换为int[,]数组?如果是,我如何将string[,]转换为int[,]?谢谢。

4 个答案:

答案 0 :(得分: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]);
    }
}

答案 1 :(得分:1)

实例: Ideone

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

转化 (请注意,当字符串= " "时,我会改为使用0

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 :(得分:1)

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

答案 3 :(得分:-1)

使用您正在使用的循环并将空字符串替换为空值,如果您要使用此数组,只需检查该值是否为空。