C# 将二维字符串数组转换为二维整数数组(多维数组)
我想替换C# 将二维字符串数组转换为二维整数数组(多维数组),c#,arrays,multidimensional-array,type-conversion,2d,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 sta
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}
};
是否可以将
字符串[,]
数组转换为int[,]
数组?如果是,如何将字符串[,]
转换为int[,]
?谢谢。使用您正在使用的循环,并用空值替换空字符串,如果要使用此数组,请先检查值是否为空。string[,]=
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]);
}
}
{
{"2", " ", " ", " ", "1"},
{"2", " ", "4", "3", " "},
{" ", "2", " ", "1", " "},
{" ", "1", " ", "3", " "},
{"1", " ", " ", " ", " "}
};
int[,]second=新int[first.GetLength(0),first.GetLength(1)];
int x=-1;
for(int i=0;i
现场示例:
Convert(请注意,当字符串=“
”时,我将放置一个0
):
int[,]second=newint[first.GetLength(0),first.GetLength(1)];
for(int j=0;j
假设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;
}
private static int[,]ConvertToIntArray(字符串[,]strArr)
{
int rowCount=strArr.GetLength(维度:0);
int colCount=strArr.GetLength(维度:1);
int[,]结果=新的int[rowCount,colCount];
对于(int r=0;r
我试图用循环解决这个问题,但我无法做到,因为X应该是空字符串“
那么,我不明白你想做什么。如果X
不是int
,则不能将其放入int
数组中。
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;
}
}
}
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;
}