Search code examples
c#arraysfiletextchar

Text from file to the end of 2d char array


I'm trying to solve the problem, but I just can't find the answer.

It is required to read a names.txt file, consisting of 5 words. After that, needs to convert them into char and then put the left side of the matrix and the bottom (look picture down). Other empty spaces need to fill with symbol "+".

I've tried many variations, but it doesn't display correctly.

Please help!

Correct output example [PNG]!

    String txtFromFile = File.ReadAllText(@"C:\Users\source\names.txt");
    Console.WriteLine("Words from file:\n{0}", txtFromFile);

    int rows = 10;
    int column = 10;
    char[,] charArray = new char[rows, column];

    for (int a = 0; a < rows; a++)
    {
        for (int b = 0; b < column; b++)
        {
            charArray[a, b] = '+';
            Console.Write(string.Format("{0} ", charArray[a, b]));
        }
        Console.Write(Environment.NewLine + Environment.NewLine);
    }

Solution

  • If you are inexperienced with Linq her is a solution without using it.

    int rows = 10;
    int column = 10;
    int lineCount = 0; //pointer variable to be used when padding lines with +
    string emptyLine = ""; 
    emptyLine = emptyLine.PadRight(column, '+'); //create empty line string
    string[] lines = File.ReadLines(@"C:\Users\source\names.txt").ToArray(); //read all lines and store in a string array variable
    
    //add lines with only +
    for (int row = 0; row < rows - lines.Length; row++)
    {
        Console.WriteLine(emptyLine);
    }
    //loop through all read lines and pad them
    foreach (string line in lines)
    {
        lines[lineCount] = lines[lineCount].Replace(line, line.PadRight(column, '+')); //pad the line and replace it in the collection
        Console.WriteLine(lines[lineCount]);
        lineCount++;
    }
    

    This solution uses string instead of char[]. However, if you need to get the array you can simply find it in the read lines collection by

    char[] charArray = lines[i].ToCharArray();
    

    for an arbitrary index i in the read lines collection.