2016-07-23 52 views
2

我有新行和空格,例如分隔作爲字符串寫入的兩位數字的網格:轉換分隔字符串到2-d陣列

string grid = "58 96 69 22 \n" + 
       "87 54 21 36 \n" + 
       "02 26 08 15 \n" + 
       "88 09 12 45"; 

我想將其分成4- by-4 array,這樣我可以通過像separatedGrid[i, j]這樣的東西來訪問它。我知道我可以使用grid.Split(' ')來分隔每一行中的數字,但是如何從中得到一個二維數組?

回答

2

所以,你想要什麼是將分隔的多行字符串轉換爲2D數組:

string grid = "58 96 69 22 \n" + 
    "87 54 21 36 \n" + 
    "02 26 08 15 \n" + 
    "88 09 12 45"; 

var lines = grid.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries) 
       .Select(x => x.Trim().Split(' ')).ToArray(); 

int numberOfRows = lines.Length; 
int maxNumberOfColumns = lines.Max(x => x.Length); 
string[,] separatedGrid = new string[numberOfRows, maxNumberOfColumns]; 

for (int i = 0; i < lines.Count(); i++) 
{ 
    string[] values = lines.ElementAt(i); 
    for (int j = 0; j < values.Length; j++) 
    { 
     separatedGrid.SetValue(values[j], i, j); 
    } 
} 
2

是使用split這樣的:

string grid = "58 96 69 22 \n87 54 21 36 \n02 26 08 15 \n88 09 12 45"; 

var jagged = grid.Split('\n').Select(
      x => new string[4] { x.Split(' ')[0], x.Split(' ')[1], x.Split(' ')[2], x.Split(' ')[3] } 
      ).ToArray(); 

如果你想有一個2-d數組:

var _2D = new String[jagged.Length, jagged[0].Length]; 
for (var i = 0; i != jagged.Length; i++) 
    for (var j = 0; j != jagged[0].Length; j++) 
     _2D[i, j] = jagged[i][j]; 

結果:

enter image description here