我试图阅读在这个格式的日志文件:分裂阵列成2个部分
date | cost
date | cost
..ect
使用以下代码来读取文件中的数组:
string[] lines = File.ReadAllLines("log.txt");
我的问题是如何将数组切分为每行2个部分,以便我可以将它们添加到2列的列表视图中?我想也许是一本字典将是一个良好的开端..
我试图阅读在这个格式的日志文件:分裂阵列成2个部分
date | cost
date | cost
..ect
使用以下代码来读取文件中的数组:
string[] lines = File.ReadAllLines("log.txt");
我的问题是如何将数组切分为每行2个部分,以便我可以将它们添加到2列的列表视图中?我想也许是一本字典将是一个良好的开端..
var lines = File.ReadAllLines("log.txt").Select(l=> l.Split('|'));
var dictionary= lines.ToDictionary(x => x[0], y => y[1]);
假设这是C#,而不是C,下面可能做你要找的内容:
public class LogEntry{
public string Date;
public string Cost;
public LogEntry(string date,string cost){
Date=date;
Cost=cost;
}
}
...
// Grab the lines from the file:
string[] lines = File.ReadAllLines("log.txt");
// Create our output set:
LogEntry[] logEntries=new LogEntry[lines.Length];
// For each line in the file:
for(int i=0;i<lines.Length;i++){
// Split the line:
string[] linePieces=lines[i].Split('|');
// Safety check - make sure this is a line we want:
if(linePieces.Length!=2){
// No thanks!
continue;
}
// Create the entry:
logEntries[i]=new LogEntry(linePieces[0] , linePieces[1]);
}
// Do something with logEntries.
注意,这种的处理只能用相对较小的日志文件来完成。 File.ReadAllLines(“log.txt”)对于大文件变得非常低效,此时使用原始FileStream更合适。
注意:安全检查可能会在logEntries数组中产生空值。它可以转换成列表
使用一个二维数组和string.Split('-')
string[] lines = File.ReadAllLines("log.txt");
//Create an array with lines.Length rows and 2 columns
string[,] table = new string[lines.Length,2];
for (int i = 0; i < lines.Length; i++)
{
//Split the line in 2 with the | character
string[] parts = lines[i].Split('|');
//Store them in the array, trimming the spaces off
table[i,0] = parts[0].Trim();
table[i,1] = parts[1].Trim();
}
现在你将有一个数组,看起来像这样:
table[date, cost]
你可以使用一个字典,所以你只需要仰望如果日期你想改善它。 编辑:作为@Damith做
此外,与LINQ你可以简化成这样:
var table = File.ReadAllLines("log.txt").Select(s => s.Split('|')).ToDictionary(k => k[0].TrimEnd(' '), v => v[1].TrimStart(' '));
,你现在可以很容易地得到来自LINQ表达式的结果具有:
foreach (KeyValuePair<string, string> kv in table)
{
Console.WriteLine("Key: " + kv.Key + " Value: " + kv.Value);
}
另请注意,如果您不需要文件中的空格,则可以省略Trim()
s
而仅仅是因为这个职位是原本标记C :)
这里是一个C例如:
与数据文件(我把它叫做TEMP.TXT),看起来像这样:
3/13/56 | 13.34
3/14/56 | 14.14
3/15/56 | 15.00
3/16/56 | 16.56
3/17/56 | 17.87
3/18/56 | 18.34
3/19/56 | 19.31
3/20/56 | 20.01
3/21/56 | 21.00
此代码将读它,它解析成一个单一的2暗淡字符串数组,char col[2][80][20];
#include <ansi_c.h>
int main()
{
int i;
char *buf;
char line[260];
char col[2][80][20];
FILE *fp;
fp = fopen("c:\\dev\\play\\temp.txt", "r");
i=-1;
while(fgets(line, 260, fp))
{
i++;
buf = strtok(line, "|");
if(buf) strcpy(col[0][i], buf);
buf = strtok(NULL, "|");
if(buf) strcpy(col[1][i], buf);
}
fclose(fp);
return 0;
}
稍微多一点的代码显示你已经做了什么将是获得更好回应的好方法 – ryyker
你的问题被标记为'c',但在你的问题中,你使用了一行C#代码。那么,你使用哪种语言? – ProgramFOX
@ProgramFOX C?我敢肯定,我标记为C#:/哎呀,我会重新标记,如果我可以 – user2864613