如何使用2d数组c#读取文件并将每个单词存储在行数组中的数组中c#

问题描述 投票:0回答:2

我正在尝试读取文本文件,然后将单词存储在2d数组中。我想要的是打开此按钮:

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;
        }

c# arrays file jagged-arrays
2个回答
0
投票

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;
}

0
投票

似乎您需要字数组或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.0mcs -out:main.exe main.cs单声道主程序System.String [] []结束

© www.soinside.com 2019 - 2024. All rights reserved.