11. CSV形式のデータから特定の項目を取り出す関数
一行の一項目を対象にしたシンプルなもの(応用で複数可)
 


文字列Sにあるカンマ区切りをデータ項目として取得します
S:対象文字列、n:項目数、extcm:取り出した文字列にカンマをつけるかどうか

function trimCSV( S :string ; n :integer ; extcm : boolean) :string;
var
        i,cn_a,cn_f,cn : integer;
begin
        cn_a := 0;
        cn_f := 0;
        cn := 0;
        result := '';
        for i := 1 to length(S) do begin
            if (copy(s,i,1) = ',') or(i = length(s)) then begin
                cn := cn +1;
                cn_f := cn_a +1;
                if (i = length(s)) and (copy(s,i,1) <> ',') then cn_a := i+1 else cn_a := i;

                  if cn = n then begin
                          result := result + copy(S,cn_f,cn_a-cn_f);
                          if extcm = true then result := result +',';
                  end;
            end;

        end;

end;

例えば、memo1にCSV形式のファイルを読み込んで、
その中の5番目の項目と6番目の項目で新しいCSV形式のデータを
memo2に出力するには ↓

procedure TForm1.Button1Click(Sender: TObject);
var
        str,str2: string;
        i : integer ;
begin
        for i := 0 to memo1.lines.count - 1 do begin
            str := trimCSV(memo1.lines[i],5,true);
            str2 := trimCSV(memo1.lines[i],6,false);
            memo2.lines.add(str+str2);
        end;

end;


追記:関数本体の条件式における(「括弧」)を忘れていました。(2002年3月4日)


戻る
竹村 匡正  takemura@sahs.med.osaka-u.ac.jp