Home > other >  Creating 2d array from a text file
Creating 2d array from a text file

Time:11-17

I have a text file that looks like this

  • 1234567891
  • a12b13c14d
  • 2122232425
  • 3132333435
  • 4142434445
  • 5152535455
  • 6162636465
  • 7172737475
  • 8182838485
  • 9192939495

in a N x N grid. using c# I need to take the text file and turn it into a 2d array of string so that I can manipulate each character on an independent level. Please help.There is no blank between characters.

String input = File.ReadAllText( @"c:\myfile.txt" );

int i = 0, j = 0;
string[,] result = new string[10, 10];
foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j  ;
    }
    i  ;
}

I tried this but there is no spaces between characters. So, I'm thinking about this.

CodePudding user response:

I would go with something like this:

var lines = File.ReadAllLines(path);

And now you can access each character. For instance, if you want the 3rd character from line 7, you can get it by lines[6][2].

You will need to add an import, if you have not already:

import System.IO;

If you want to convert it to digits also, you can do a method like this:

// somewhere outside the method you should have read the lines and stored them in a variable:
var lines = File.ReadAllLines(path);

// the method to access a position and convert it to digit
int AccessDigit(string[] lines, int row, int col)
{
    // code that checks if row and col are not outside the bounds should be placed here

    // if inside bounds, we can try to access and convert it
    var isDigit = int.TryParse(lines[row][col], out int digit);

    return isDigit ? digit : -1;
}

And then you would call it like this:

var digit = AccessDigit(lines, 6, 2);

Hope this helps. If my answer still does not help you, please tell me and I'll update my answer.

  • Related