1

次の内容を含むテキスト ファイルがあります: (引用符と「空のスペース」なし)

  • ##############
  • # 空きスペース#
  • # 空きスペース#
  • # 空きスペース#
  • # 空きスペース#
  • ##############

このファイル全体を行ごとにリストに追加したい:

FileStream FS = new FileStream(@"FilePath",FileMode.Open);
StreamReader SR = new StreamReader(FS);
List<string> MapLine = new List<string>();

foreach (var s in SR.ReadLine())
{
    MapLine.Add(s.ToString());                   
}

foreach (var x in MapLine)
{
    Console.Write(x);
}

ここに私の問題があります。これを 2 次元配列に追加したいのです。私は試した:

string[,] TwoDimentionalArray = new string[100, 100];

for (int i = 0; i < MapLine.Count; i++)
{
    for (int j = 0; j < MapLine.Count; j++)
    {
        TwoDimentionalArray[j, i] = MapLine[j].Split('\n').ToString();
    }
}

私はまだC#に慣れていないので、助けていただければ幸いです。

4

2 に答える 2

0

現在、ファイルのすべての行を調べており、ファイルのすべての行について、ファイルのすべての行をもう一度\n調べて、MapLine.

行配列のすべての単一の文字が必要な場合、それを再び配列に入れると、おおよそ次のようになります。

string[,] TwoDimentionalArray = new string[100, 100];

for (int i = 0; i < MapLine.Count; i++)
{
     for (int j = 0; j < MapLine[i].length(); j++)
     {
          TwoDimentionalArray[i, j] = MapLine[i].SubString(j,j);
     }
}

これはテストせずに行ったので、間違っている可能性があります。ポイントは、最初に各行を反復処理し、次にその行の各文字を反復処理する必要があるということです。そこから、 を使用できますSubString

また、あなたの質問を正しく理解できたことを願っています。

于 2013-02-11T14:02:10.863 に答える
0

これで試すことができます:

        // File.ReadAllLines method serves exactly the purpose you need
        List<string> lines = File.ReadAllLines(@"Data.txt").ToList();

        // lines.Max(line => line.Length) is used to find out the length of the longest line read from the file
        string[,] twoDim = new string[lines.Count, lines.Max(line => line.Length)];

        for(int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
            for(int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
                twoDim[lineIndex,charIndex] = lines[lineIndex][charIndex].ToString();

        for (int lineIndex = 0; lineIndex < lines.Count; lineIndex++)
        {
            for (int charIndex = 0; charIndex < lines[lineIndex].Length; charIndex++)
                Console.Write(twoDim[lineIndex, charIndex]);

            Console.WriteLine();
        }

        Console.ReadKey();

これにより、ファイル コンテンツの各文字が 2 次元配列内の独自の位置に保存されます。その目的のためchar[,]にも使用された可能性があります。

于 2013-02-11T14:08:39.557 に答える