2013-10-12 182 views
0

我試圖閱讀在這個格式的日誌文件:分裂陣列成2個部分

date | cost 
date | cost 
..ect 

使用以下代碼來讀取文件中的數組:

string[] lines = File.ReadAllLines("log.txt");

我的問題是如何將數組切分爲每行2個部分,以便我可以將它們添加到2列的列表視圖中?我想也許是一本字典將是一個良好的開端..

+1

稍微多一點的代碼顯示你已經做了什麼將是獲得更好迴應的好方法 – ryyker

+8

你的問題被標記爲'c',但在你的問題中,你使用了一行C#代碼。那麼,你使用哪種語言? – ProgramFOX

+1

@ProgramFOX C?我敢肯定,我標記爲C#:/哎呀,我會重新標記,如果我可以 – user2864613

回答

1
var lines = File.ReadAllLines("log.txt").Select(l=> l.Split('|')); 
var dictionary= lines.ToDictionary(x => x[0], y => y[1]); 
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更合適。

+0

注意:安全檢查可能會在logEntries數組中產生空值。它可以轉換成列表,但可能不會表現良好。 –

0

使用一個二維數組和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

0

而僅僅是因爲這個職位是原本標記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; 
}