[英]Convert 2D string array into 2D int array (Multidimensional Arrays)
我想替換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[,]
? 謝謝。
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]);
}
}
現場示例: 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;
}
}
}
假設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.