【问题标题】:How to read a file and store each word in a array in a array of lines using 2d arrays c#如何使用二维数组读取文件并将每个单词存储在数组中的行数组中c#
【发布时间】:2020-04-25 20:24:29
【问题描述】:

我正在尝试读取文本文件,然后将单词存储在二维数组中。我想要的是把这个:

a b c d e f g
h i j k l m n
o p q r s t u

变成

[ [a,b,c,d,e,f,g], [h,i,j,k,l,m,n], [o,p,q,r,s,t,u] ]

所以在一个数组内,每一行都有自己的数组,在该数组内,每个单词(在这种情况下只有字符)都是它自己的项目。

        {
            string[] lines = system.IO.File.ReadAllLines(@FilePath);
            foreach (string line in lines)
            {
                //no idea what to put here
            }
            return contents;
        }

【问题讨论】:

  • string[][] jaggedArray = lines.Select(x => x.Split(' ')).ToArray();

标签: c# arrays file jagged-arrays


【解决方案1】:

使用 Linq 的解决方案

var result = File.ReadAllLines("C://text.txt").Select(l => l.Split(' ', StringSplitOptions.RemoveEmptyEntries)).ToArray();

锯齿状数组的解决方案

var lines = File.ReadAllLines("C://text.txt");
var array = new string[lines.Length][];
for (int i = 0; i < lines.Length; i++)
{
    var line = lines[i].Split(' ', StringSplitOptions.RemoveEmptyEntries);
    array[i] = line;
}

【讨论】:

    【解决方案2】:

    看起来你想要一个单词数组,或者string[][]

    // example of what you're reading from the file
    var lineArray = new [] {
      "The quick brown fox",
      "Jumped over the lazy",
      "dog from a text file"
    };
    
    // 2d array output string[][]
    var result = lineArray
      .Select(ln => ln.Split(' '))
      .ToArray();
    
    // result type, should be string[][]
    Console.WriteLine(result);
    
    // should be the word "over"
    Console.WriteLine(result[1][1]);
    

    Mono C# 编译器版本 4.6.2.0 mcs -out:main.exe main.cs 单声道主程序 System.String[][] 结束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 2016-01-24
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多