[英]How to read a text file and save all the file content into a two-dimensional character array in C#
我真的從你們那里得到了幫助。 我是 C# 的新手,老實說,現在我正在盡最大努力學習。 不管怎樣,故事講得夠多了。 我有一個文本文件,我想用StreamReader
讀取它,然后將文件的所有內容保存到一個字符數組中並關閉文件。
其中,我成功讀取了文件內容,但現在的挑戰是將內容保存到一個字符數組中,然后使用二維顯示其內容。 這是我到目前為止所擁有的!
負責文件讀取的函數
private void ReadConfigFile()
{
try
{
StreamReader inputFile; // To read the config file
count = 0; //config file counter variable
inputFile = File.OpenText(@"config.txt"); //open the config file
while (!inputFile.EndOfStream)
{
configFile = inputFile.ReadLine(); //reads the config file
count++;
}
inputFile.Close();
numOfLines = count;
//MessageBox.Show($"{numOfLines.ToString()}"); //For debugging
JaggedArray(configFile, numOfLines);
//Display();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Configuration File", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
以及,實際顯示二維char數組的函數
private void JaggedArray(string config, int numberOfLines)
{
boardArray = new char[numberOfLines][]; //Character array of the configuration file
for (int r = 0; r < boardArray.Length; r++) //looping through rows of gameboard
{
r = 0;
for (int c = 0; c < boardArray[r].Length; c++) //looping through columns of gameboard
{
MessageBox.Show(boardArray[r][c].ToString()); //For debugging
}
}
}
我打算實現的是能夠將文件放入二維字符數組中,並且還知道如何在其他JaggedArray
函數中使用它來操作它。 我會非常感謝任何幫助呈現給我。 拜托,我只是懇求,僅此而已。
如果要將文件的上下文保存到鋸齒狀數組中,建議使用Linq :
using System.IO;
using System.Linq;
...
char[][] data = File
.ReadLines(@"config.txt")
.Select(line => line.ToCharArray())
.ToArray();
要一次性顯示數組,您可以使用string.Join
和Linq
string result = string.Join(Environment.NewLine, data
// .Take(numberOfLines) // if you want to take just numberOfLines top lines
.Select(line => string.Join("; ", line))); // put "" if you want to concat the chars
Console.Write(result);
基於循環的實現:
foreach (var line in data) {
Console.WriteLine();
foreach (char c in line) {
Console.Write(c);
Console.Write(' ');
}
}
如果我理解正確,您想將每一行的字符添加到一個字符數組中,然后將這些字符數組放入一個“容器”數組中(在這種情況下,它將是一個字符數組而不是兩個維數組。請注意,多維數組是另一回事,您可以在這篇 MSDN 文章中了解更多信息。
回到您的問題,您可以使用類似以下函數的內容以所需格式(字符數組的數組)返回文件內容:
//A function that will read a file and return an array of an array of char.
char[][] ReadFileLinesAsArraysOfChar(string filePath)
{
//Create a list of array of char.
var lines = new List<char[]>();
string line;
StreamReader file = new StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
//Convert each line into a char array and add to the list.
lines.Add(line.ToCharArray());
}
//Convert the list to an array (of array of char) and return.
return lines.ToArray();
}
用法:
//Create the array from file.
var boardArray = ReadFileLinesAsArraysOfChar(@"config.txt");
//Display each line in a message box for demonstration.
foreach (char[] line in boardArray)
{
//Using 'new string()' to convert the char array back to a string.
MessageBox.Show(new string(line));
}
希望有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.