[問題] 2d array 要如何寫入txt檔 (已解決)
如題。
(二維矩陣是當下臨時產生的)
部分code如下
//這是隨機產生一個10X2的矩陣,並將int 轉成string
string[,] OutputArray = new string[10, 2];
Random rnd = new Random();
for (int i = 0; i < OutputArray.GetLength(0); i++)
{
for (int j = 0; j < OutputArray.GetLength(1); j++)
{
OutputArray[i, j] = Convert.ToString(rnd.Next(1, 10));
}
}
System.IO.File.WriteAllLines("c:\\file.txt", OutputArray);
****錯誤訊息
引數 2: 無法從 'string[*,*]' 轉換為 'string[]'
我GOOGLE很多,參考到了一篇文章。差別就是我的是二維,他的是一維...
http://net-informations.com/csprj/collection/cs-stringarray.htm
code如下:
string[] months = new string[12];
months[0] = "Jan";
months[1] = "Feb";
months[2] = "Mar";
months[3] = "Apr";
months[4] = "May";
months[5] = "Jun";
months[6] = "Jul";
months[7] = "Aug";
months[8] = "Sep";
months[9] = "Oct";
months[10] = "Nov";
months[11] = "Dec";
System.IO.File.WriteAllLines("c:\\file.txt", months);
我最後的輸出是要長這樣
A0 A1
B0 B1
C0 C1
...
..
.
就是每一列元素跟元素之間會參雜 \t (就是TAB鍵),這樣用excel打開就會一格一格的
每一行之會參雜 \n (就是按鍵的enter,換行的意思)。
前面問題解決的話這邊就應該不難,就穿插\t 跟 \n而已。
謝謝大家!
--
--
▂▂ ▂▂▂
▂▄▅▅▄▆█ _█◣
◢ (●) ◣/\\
丫 │◥  ̄◤
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.20.4
→
10/14 22:23, , 1F
10/14 22:23, 1F
謝謝~昨天想了想,還是轉成一維就好~
因為我參考到這篇是一維的~"~
code如下
/*宣告陣列*/
List<string>[] OutputArray = new List<string>[10];
string[] result = new string[10];
/*初始畫List OutputArray*/
for (int i = 0; i < OutputArray.GetLength(0); i++)
{
OutputArray[i] = new List<string>();
}
/*隨機產生10組變數,每一組有5個*/
Random rnd = new Random();
for (int i = 0; i < OutputArray.GetLength(0); i++)
{
for (int j = 0; j < 5; j++)
{
OutputArray[i].Add(Convert.ToString(rnd.Next(1, 10)));
}
/*將每一組5個變數加入 \t */
result[i] = String.Join("\t", OutputArray[i].ToArray());
}
/*輸出到file.txt*/
System.IO.File.WriteAllLines(@"c:\\file.txt", result);
我去C槽看,用excel開啟是整齊的~
※ 編輯: sqrt1089 來自: 140.116.20.4 (10/15 09:59)