![](/img/trans.png)
[英]How to read a file and store each word in a array in a array of lines using 2d arrays c#
[英]read file and store values into a 2D array
我有一个包含以下内容的文件:
S5555; 100 70 70 100
S3333; 50 50 50 50
S2222; 20 50 40 70
S1111; 90 80 90 85
S4444; 70 80 90 50
用户单击按钮1时,应将存储学生ID的文件加载到studentIDArr中(例如S5555),将其他值加载到4x5数组marksMatrix中,每个值在数组中占据一个位置。
我是否将值正确存储到studentIDArr中? 至于marksMatrix,我试图粗略地写出我认为它是如何工作的,但是我也不是很确定(有人评论了)。 我只能为此使用数组。
string[,] marksMatrix = new string[4,5];
string[] studentIDArr = new string[5];
private void button1_Click(object sender, EventArgs e)
{
textBox2.Clear();
try
{
using (StreamReader sr = new StreamReader("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
{
string x = null;
while ((x = sr.ReadLine()) != null)
{
for (int j = 0; j < studentIDArr.Length; j++)
{
studentIDArr[j] = x;
}
}
}
textBox2.Text = "File Loading done.\r\n";
textBox2.Text += "Number of records read: " + studentIDArr.Length;
}
catch (IOException ex)
{
textBox2.Text = "The file could not be read. " + ex.Message;
}
string a, b, c;
for (int i = 0; i < studentIDArr.Length; i++)
{
//a = (String)studentIDArr[i];
// string[] abc = Regex.Split(a, ";");
// b = abc[0];
// c = abc[1];
// bc =;
for (int y = 0; y < 6; y++)
{
for (int x = 0; x < 5; x++)
{
//marksMatrix[y, x] = z;
}
}
}
button1.Enabled = false;
}
您可以使用for循环简单地做到这一点。
string[,] marksMatrix = new string[4, 5];
string[] studentIDArr = new string[5];
var lines = File.ReadAllLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt");
for (int i = 0; i < lines.Length; i++)
{
var parts = lines[i].Split(new[] {';', ' ' });
studentIDArr[i] = parts[0];
for (int j = 1; j < parts.Length; j++)
{
marksMatrix[j - 1, i] = parts[j];
}
}
这种编码方式难以理解,请尝试定义一个类来存储学生ID和标记。
public class Student
{
public string Id { get; set; }
public List<string> Marks { get; set; }
public Student()
{
this.Marks = new List<string>();
}
}
然后代码将如下所示
var students = new List<Student>();
foreach (var line in File.ReadLines("C:/Users/Y400/dDesktop/CTPrac/CTPrac/input.txt"))
{
var parts = line.Split(new[]{';', ' '}).ToList();
students.Add(new Student()
{
Id = parts[0],
Marks = parts.GetRange(1, 4)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.