从文件到二维字符数组末尾的文本

Text from file to the end of 2d char array

我正在尝试解决问题,但我就是找不到答案。

需要读取一个names.txt文件,由5个单词组成。之后,需要将它们转换成char,然后把矩阵的左边和底部(看下图)。其他空白需要用符号"+".

填充

我试过很多变体,但显示不正确。

请帮忙!

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

你可以一行完成,

using System.Linq;    

...

//Read all lines instead of reading all inputs in form of text.
//Note: Expecting all words should be are stored on different line. 
string[] txtFromFile = File.ReadAllLines(@"C:\Users\source\names.txt");

var result = Enumerable.Range(0, 10) //Iterate for 10 lines
       .Select(x => x < 5  // Check for line number
          ? new string('+', 10)   //If line is from 0..4, then print ++++++++++
          : txtFromFile[x-5].PadRight(10, '+') //else print word then pad it with ++
       );

 //Print the result
 Console.WriteLine(string.Join(Environment.NewLine, result));

.NET Fiddle

输出:

++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
DOG+++++++
SHEEP+++++
CHIMPANZEE
BREAVER+++
LION++++++

如果您对 Linq 没有经验,她是一个无需使用的解决方案。

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

此解决方案使用 string 而不是 char[]。但是,如果您需要获取数组,您可以通过

在读取行集合中简单地找到它
char[] charArray = lines[i].ToCharArray();

对于读取行集合中的任意索引 i