首页 > 解决方案 > 从文件到二维字符数组末尾的文本

问题描述

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

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

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

请帮忙!

正确的输出示例 [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);
    }

标签: c#arraysfiletextchar

解决方案


如果您对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


推荐阅读