c# - 从文件到二维字符数组末尾的文本
问题描述
我正在尝试解决问题,但我找不到答案。
需要读取一个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);
}
解决方案
如果您对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
。
推荐阅读
- javascript - 将值从计算机插入另一台计算机时出现“ER_HOST_NOT_PRIVILEGED”
- python - Flask:由于 KeyError,应用程序无法运行
- python - 在python中为每个条拆分midi文件
- javascript - 为什么我们不能使用 ES6 箭头函数创建原型?
- javascript - 在新窗口中打开的 Web 资源中使用 Xrm.WebApi 方法
- java - Twincat ADS 事件驱动的读取在一段时间后停止工作(Java)
- yaml - 如何在 CloudWatch 警报中传递 EMR 集群 ID
- c++ - 如何删除选定的图形项组?
- deep-learning - 减小 fasttext bin 文件的大小
- javascript - 过滤包含 Javascript 中特定符号或单词的数组