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