2016-11-20 164 views
1

我想更换string[,]二维数组转换2D字符串数组为二维int数组(多维数组)

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

+0

我试图用一个循环来解决这个问题,但我不能这样做,因为X应该是空字符串'“”' – tamaramaria

+0

我不明白你想要做什么,然后。如果'X'不是'int',那么你不能把它放在'int'数组中。 – smarx

回答

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

使用你正在使用的循环,并用空值替换空字符串,如果你要使用这个数组,只要检查值是否为空。

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

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