我有一个文本文件,加载到一个字符串数组中。该文件的内容如下所示:
OTI*IA*IX*NA~ 参考文献*G1*J EVERETTE~ 参考文献*11*0113722462~ AMT*GW*229.8~ NM1*QC*1*JENNINGS*PHILLIP~ OTI*IA*IX*NA~ 参考文献*G1*J EVERETTE~ 参考文献*11*0113722463~ AMT*GW*127.75~ NM1*QC*1*JENNINGS*PHILLIP~ OTI*IA*IX*NA~ 参考文献*G1*J EVERETTE~ 参考文献*11*0113722462~ AMT*GW*10.99~ NM1*QC*1*JENNINGS*PHILLIP~ ..。
我正在寻找以OTI开头的行,如果后面是"IA“,那么我需要从以REF*11开头的行中得到10位数的数字。到目前为止,我有以下内容:
string[] readText = File.ReadAllLines("myfile.txt");
foreach (string s in readText) //string contains 1 line of text from above example
{
string[] currentline = s.Split('*');
if (currentline[0] == "OTI")
{
//move down 2 lines and grab the 10 digit
//number from the line that starts with REF*11
}
}我需要的线路总是在当前OTI线之后的2行。如何访问从当前线路向下2行的线路?
发布于 2012-10-29 17:43:27
那麽:
string[] readText = File.ReadAllLines("myfile.txt");
for (int i = 0; i < readText.Length; i++)
{
if (readText[i].StartsWith("OTI") && readText[i+2].StartsWith("REF*11")){
string number = readText[i+2].Substring("REF*11".Length, 10);
//do something
}
}发布于 2012-10-29 17:34:40
不使用foreach(),您可以使用for(int index = 0; index < readText.Length; index++),这样您就知道您正在访问的行了,您可以轻松地说出int otherIndex = index + 2
string[] readText = File.ReadAllLines("myfile.txt");
for(int index = 0; index < readText.Length; index++)
{
string[] currentline = readText[index].Split('*');
if (currentline[0] == "OTI")
{
//move down 2 lines and grab the 10 digit
//number from the line that starts with REF*11
int refIndex = index + 2;
string refLine = readText[refIndex];
}
}发布于 2012-10-29 17:37:53
这看起来像个EDI文件!啊,艾迪,记忆..。
好消息是EDI文件是分隔的,就像大多数CSV文件格式一样。您可以使用任何标准的CSV文件库将EDI文件加载到一个巨大的数组中,然后按位置迭代它。
我在这里发布了我的开源CSV库,如果有用的话可以随意使用它。您只需将“星号”指定为分隔符:
https://code.google.com/p/csharp-csv-reader/
// This code assumes the file is on disk, and the first row of the file
// has the names of the columns on it
DataTable dt = CSVReader.LoadDataTable(myfilename, '*', '\"');此时,您可以正常地遍历datatable。
for (int i = 0; i < dt.Rows.Count; i++) {
if (dt.Rows[i][0] == "OTI") {
Console.WriteLine("The row I want is: " + dt.Rows[i + 2][0]);
}
}https://stackoverflow.com/questions/13126702
复制相似问题