簡體   English   中英

將數組拆分為2個部分

[英]Splitting an array into 2 parts

我試圖以這種格式讀取日志文件:

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更合適。

使用2D數組和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()

並且因為這篇文章最初被標記為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 dim字符串數組, 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM