我正在尝试将输入文件读入数组.我的文件看起来像:
00000*5071177*M010165767HAZZ JONES FAKE B M12/16/196901/06/2014000000036209 00000*5071178*M0201657677315 FAKE ST MOON TX56464 485942934 MAINTENCE
当第一行的第一个单词中的模式与第二行的第二个块中的模式匹配时,我希望将由空格分解的整行划分为数组或对象.
所以我的数组将包含类似 [5071177] - >数组([琼斯,假,B,M12/16/196901,假ST,月亮等]); 什么是实现这一目标的最佳方法?
StreamReader sR = new StreamReader("Desktop/records2.txt");
StreamWriter sW = new StreamWriter("Desktop/new.txt");
while (sR.Peek() != -1) // stops when it reachs the end of the file
{
string line = sR.ReadLine();
// var myArray = line.Split('\n');
string[] myarray = line.Split(' ');
// "line" EDITING GOES HERE
sW.WriteLine(myarray); /
}
Run Code Online (Sandbox Code Playgroud)
首先创建一个类来保存您的数据:
public Record
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DateOfBirth { get; set; }
/* etc */
}
Run Code Online (Sandbox Code Playgroud)
在另一个类中创建一个方法,类似于Parse()返回一个Record.
public class RecordParser
{
private List<string> rawRecords;
public RecordParser()
{
rawRecords = new List<string>();
}
public RecordParser(string filePath)
{
rawRecords = new List<string>();
rawRecords.AddRange(ReadLines(filePath));
}
public Record Parse(string raw)
{
// 00000*5071177*M010165767HAZZ JONES FAKE B M12/16/196901/06/2014000000036209
string[] myarray = line.Split(' ');
Record record = new Record
{
Id = myarray[0].Split('*')[1],
FirstName = myarray[1],
LastName = myarray[2],
DateOfBirth = myarray[3],
/* etc */
};
return record;
}
public List<Record> ParseAll()
{
if(!rawRecords.Any()) throw new ArgumentNullException("Nothing to parse.");
var records = new List<Record>();
foreach(string raw in rawRecords)
{
records.Add(Parse(raw));
}
return records;
}
private List<string> ReadLines(string path)
{
// exception handling needed.
return File.ReadLines(path).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var recordParser = new RecordParser();
string data = "00000*5071177*M010165767HAZZ JONES FAKE B M12/16/196901/06/2014000000036209";
Record record = recordParser.Parse(data);
var recordParser = new RecordParser(@"C://data.txt");
List<Record> records = recordParser.ParseAll();
Run Code Online (Sandbox Code Playgroud)