2016-11-20 167 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; 
}