将二维字符串数组转换为二维整数数组(多维数组) [英] Convert 2D string array into 2D int array (Multidimensional Arrays)

查看:71
本文介绍了将二维字符串数组转换为二维整数数组(多维数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换string[,]二维数组

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[,] ?谢谢.

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

推荐答案

实例: Ideone

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

转换 (注意,当字符串 = " " 时,我将使用 0 代替):

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

这篇关于将二维字符串数组转换为二维整数数组(多维数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆