字符串列表和CSV [英] Stringlist and CSV

查看:97
本文介绍了字符串列表和CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将CSV文件加载到其中后,如何基于Stringlist中的索引访问单个记录。

How can i access the individual records based on Index in Stringlist after loading this CSV file in to it.

CSV示例:

   Record0;Record1;Record2
   Record0;Record1;Record2
   Record0;Record1;Record2
   Record0;Record1;Record2


推荐答案

SplitString 将使用您定义的定界符分割字符串。
在此示例中,;和;

SplitString will split your string with delimiters you define. In this example space and ; character.

更新

添加了索引拆分函数的示例。 ( SplitByIndex )。

Added an example of an indexed split function. (SplitByIndex).

更新2

添加了一个示例( SplitByIndexAlt )不使用 SplitString ,而是使用 TStringList .DelimitedText
这将处理空格和;作为分隔符(不是 QuoteChar 所包含的分隔符)。

Added an example (SplitByIndexAlt) not using SplitString, but TStringList.DelimitedText. This will treat spaces and ; as delimiter (not the ones enclosed by QuoteChar).

uses
  SysUtils,Classes,System.Types,System.StrUtils;

procedure Test(aStringList: TStringList);
var
  s,split : String;
  splittedString : TStringDynArray;
begin
  for s in aStringList do begin
    splittedString := SplitString(s,' ;'); // Splits at space and ;
    for split in splittedString do
    begin
      WriteLn(split);
    end;
  end;    
end;


Function SplitByIndex(aList : TStringList; aRow,aCol : Integer) : String;
// Zero based index !
var
  splittedString : TStringDynArray;
begin
  Result := '';
  if (aRow < aList.Count) then
  begin
    splittedString := SplitString(aList[aRow],' ;');
    if (aCol < Length(splittedString))
      then Result := splittedString[aCol];
  end;    
end;


Function SplitByIndexAlt(aList : TStringList; aRow,aCol : Integer) : String;
// Zero based index !
var
  splitlist : TstringList;
begin
  Result := '';
  if (aRow < aList.Count) then
  begin
    splitList := TStringList.Create;
    Try
      splitList.Delimiter := ';';
      // splitList.QuoteChar := '"'; // This may have to be changed
      splitList.StrictDelimiter := false;
      splitList.DelimitedText := aList[aRow];
      if (aCol < splitList.Count)
        then Result := splitList[aCol];
    Finally
      splitList.Free;
    End;
  end;
end;


var
  myList: TStringList;
begin
  myList := TStringList.Create;
  Try
    myList.Add('#0  Record0;Record1;Record2');
    myList.Add('#1  Record0;Record1;Record2');
    myList.Add('#2  Record0;Record1;Record2');
    myList.Add('#3  Record0;Record1;Record2');
    Test(myList);
    WriteLn(SplitByIndex(myList,0,4);
    ReadLn;
    Finally
      myList.Free;
    End;
end.

此处的输出如下:

#0

Record0
Record1
Record2

etc

现在缺点如果未标准化CSV文件格式,请参见 CSV Wiki
因此,对于更通用的解决方案,该解决方案可能看起来更复杂。

Now consider that a CSV file format is not standardised, see CSV Wiki. So for a more general solution the solution might look more complex.

这篇关于字符串列表和CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆