1

I want to take the contents of a text file and place it into a 2D array, character by character. I have included an example below

Text File

ABCDE
FGHIJ
KLMOP

2D Array (Char Array)

[
 [A,B,C,D,E]
 [F,G,H,I,J]
 [K,L,M,O,P]
]

What would be the best way of going about this? For the time being I am assuming that the length of the text file is also the width (in Char), I will fix it up later!

OpenFileDialog openFile1 = new OpenFileDialog();
string sFileName = openFile1.FileName;

int lineCount = File.ReadLines(sFileName).Count();

char[,] letters = new char[lineCount,lineCount];
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
Timbats1993
  • 55
  • 1
  • 5
  • Read the accepted answer on [this question.](http://stackoverflow.com/questions/20614694/how-to-convert-jagged-array-to-2d-array) I believe it answers your question exactly. – Zohar Peled Aug 27 '15 at 04:59

1 Answers1

3

Use File.ReadLines and then String.ToCharArray

StringBuilder lines = new StringBuilder();
foreach (string line in File.ReadLines(sFileName))
{
   lines.Append(line);
}
char[] char_array = lines.ToString().ToCharArray();

EDIT: When needing 2D array line by line;

List<char[]> lines = new List<char[]>();
foreach (string line in File.ReadLines(sFileName))
{
   lines.Append(line.ToCharArray());
}
char[] char_array = lines.ToArray();
Community
  • 1
  • 1
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
  • What should `lines.ToString()` do? – joe Aug 27 '15 at 04:49
  • @joe this is the concatenated string from the StringBuilder but is irrelevant for an array of lines with each line a char array. (oops I now see you mean with the edit - just bad cut-n-paste!) – Dave Anderson Aug 27 '15 at 04:52
  • @Zohar missed that looking at the example but updated now – Dave Anderson Aug 27 '15 at 04:53
  • @Zohar yes thanks :o) only when I saw your edit did I realise I was a bit too quick off the mark! – Dave Anderson Aug 27 '15 at 04:56
  • this creates a jagged array (char[][]), not a multidimensional array (char[,]). – davcs86 Aug 27 '15 at 04:57
  • 3
    btw, I think your second attempt will create a jagged array, and not a 2d arrray. However, a jagged array is better suited for storing lines from a file, since there is no guarantee that the lines will all have the same number of characters... – Zohar Peled Aug 27 '15 at 04:57