1
我有一個名爲Labyrint的文本文件,我讀入一個char數組。之後,我將char數組讀入一個沒有\ n(換行符)的列表中。在我這樣做後,我將列表轉換爲數組。現在我想讓這個數組成爲一個二維數組,但我該怎麼做。這是labyrint的圖像,尺寸爲21x21,尺寸爲Labyrint。以下是我的代碼:將數組轉換爲二維數組的問題
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace ConsoleApplication25
{
class Program
{
static char[] FloridaArray;
static string DenverString;
static string[,] names = new string[21, 21];
static List<object> wrd = new List<object>();
static void Main(string[] args)
{
//Increase Console Buffer Height
Console.BufferHeight = Int16.MaxValue - 1;
DenverString = ConvertStringArrayToString();
FloridaArray = DenverString.ToArray();
Console.WriteLine(DenverString);
for (int i = 0; i < FloridaArray.Length; i++)
{
if (FloridaArray[i] != '\n')
{
wrd.Add(FloridaArray[i].ToString());
}
}
foreach (object o in wrd)
{
Console.WriteLine(o);
}
//Here I check what index 21 contain in the list called wrd
Console.WriteLine("Here I check if index 21 contain character B: " + wrd[21]);
Console.WriteLine(wrd.GetType());
// Here I convert the list called wrd to an array.
object[] myArray = wrd.ToArray();
// Here I check what character is in index 21 in the array called myArray.
Console.WriteLine(myArray[21]);
//Here I look up the data type of myArray
Console.WriteLine(myArray.GetType());
for (int j = 0; j < 21; j++)
{
for (int i = 0; i <= 21; i++)
{
// how do I put the value from my char array into the two dimensional array?
names[j, i] = myArray[i].ToString();
Console.WriteLine(j + " names " + i);
}
}
}
static string ConvertStringArrayToString()
{
// Concatenate all the elements into a StringBuilder.
StringBuilder builder = new StringBuilder();
foreach (var value in File.ReadAllLines("Labyrint.txt", Encoding.UTF8).Skip(1))
{
builder.Append(value);
builder.Append('\n');
}
return builder.ToString();
}
}
}
感謝您的回覆@DavidG它解決了這個問題。我唯一需要改變的是21到20(因爲當我在文件中讀取時,我跳過了1行),但是我離開myArray [j * 21 + i]爲21,否則它會給我錯誤的索引。如果你看到這個評論,你不能解釋爲什麼你用21乘以j?那部分我真的不明白? – cop77