[英]Convert 2D string array into 2D int array (Multidimensional Arrays)
I want to replace string[,]
2D array 我想替换string[,]
2D数组
public static readonly string[,] first =
{
{"2", " ", " ", " ", "1"},
{"2", " ", "4", "3", " "},
{" ", "2", " ", "1", " "},
{" ", "1", " ", "3", " "},
{"1", " ", " ", " ", " "}
};
into int[,]
array 到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}
};
Is it possible to convert a string[,]
array to an int[,]
array? 是否可以将string[,]
数组转换为int[,]
数组? If yes, how can I convert the string[,]
into int[,]
? 如果是,如何将string[,]
转换为int[,]
? Thank you. 谢谢。
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]);
}
}
Live example: Ideone 现场示例: 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) : 转换 (请注意,当字符串= " "
,我改为使用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;
}
}
}
Assuming X = -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;
}
使用您正在使用的循环,并将空字符串替换为null值,如果要使用此数组,只需检查该值是否不为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.