10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Delphi TStringListの使い方

Posted at

この記事ではDelphiの文字列リスト操作クラスのTStringListでよく使うパターンを列挙しました。

#まずはこれが基本ですね
TStringListに限ったことではないですがObjectを操作する場合、try, finallyでcreateしたら必ずfreeされるようにしておきます。

uses
Classes;

var
 sl:TStringList;
begin
 sl := TStringList.Create;
 try
  //ここでいろいろ処理
 finally
  sl.Free;
 end;

#Add, Delete

var
 sl:TStringList;
begin
 sl := TStringList.Create;
 try
  sl.Add('1');
  sl.Add('2');
  sl.Delete(0); //0番目を削除
 finally
  sl.Free;
 end;

#Iterate

var
  sl:TStringList;
  i:integer;
begin
  sl := TStringList.Create;
  try
    for i := 0 to sl.Count - 1 do begin
      WriteLn(sl[i]);
    end;
  finally
    sl.Free;
  end;

#カンマ区切りテキスト

var
  sl:TStringList;
  i:integer;
begin
  sl := TStringList.Create;
  try
    sl.CommaText := 'a,b,c,d';

    WriteLn(sl[0]); // a
    WriteLn(sl[1]); // b
    WriteLn(sl[2]); // c
    WriteLn(sl[3]); // d

    sl.Add('e');

    WriteLn(sl.CommaText); //a,b,c,d,e
  finally
    sl.Free;
  end;

#Delimiterを指定すれば、タブ区切りテキストなども操作可能

var
  sl:TStringList;
  i:integer;
begin
  sl := TStringList.Create;
  try
    sl.Delimiter := #9;
    sl.CommaText := 'a#9b#9c#9d';

    WriteLn(sl[0]); // a
    WriteLn(sl[1]); // b
    WriteLn(sl[2]); // c
    WriteLn(sl[3]); // d

    sl.Add('e');

    WriteLn(sl.CommaText); //a#9b#9c#9d#9e
  finally
    sl.Free;
  end;

#IndexOfで要素の位置(0オリジン)を取得

'''delphi
var
sl:TStringList;
i:integer;
begin
sl := TStringList.Create;
try
sl.Add('a');
sl.Add('b');
sl.Add('c');

WriteLn(sl.IndexOf('a'));   // 0
WriteLn(sl.IndexOf('b'));   // 1
WriteLn(sl.IndexOf('c'));   // 2
WriteLn(sl.IndexOf('xxx')); // -1

finally
sl.Free;
end;
'''

#連想配列

var
  sl:TStringList;
  i:integer;
begin
  sl := TStringList.Create;
  try
    sl.Values['a'] := '1';
    sl.Values['b'] := '2';
    sl.Values['c'] := '3';

    for I := 0 to sl.Count - 1 do begin
      WriteLn(sl.Names[i]);          //a
      WriteLn(sl.ValueFromIndex[i]); //1
      WriteLn(sl[i]);                //a=1
    end;

    WriteLn(sl.IndexOfName('a')); //0
  finally
    sl.Free;
  end;
10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?