简体   繁体   中英

How to read a file and store each word in a array in a array of lines using 2d arrays c#

I am trying to read a text file and then store the words in a 2d array. What I am wanting is to turn this:

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

Turns into

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

So inside of one array, each line gets its own array and inside of that array each word(in this case only characters) is its own item.

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

Solution with Linq

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

Solution with jagged arrays

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

It looks like you're wanting an array of word arrays, or 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# compiler version 4.6.2.0 mcs -out:main.exe main.cs mono main.exe System.String[][] over

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM