TStringList 的使用方法详解2

来源:百度文库 编辑:神马文学网 时间:2024/05/02 20:53:00
//避免重复值
var
  List: TStringList;
begin
  List := TStringList.Create;

  List.Add('aaa');

  List.Sorted := True; //需要先指定排序
  List.Duplicates := dupIgnore; //如有重复值则放弃

  List.Add('aaa');

  ShowMessage(List.Text); //aaa

//Duplicates 有3个可选值:
//dupIgnore: 放弃;
//dupAccept: 结束;
//dupError: 提示错误.

  List.Free;
end;



//排序与倒排序
{排序函数}
function DescCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
  Result := -AnsiCompareText(List[Index1], List[Index2]);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  List: TStringList;
begin
  List := TStringList.Create;

  List.Add('bbb');
  List.Add('ccc');
  List.Add('aaa');

//未排序
  ShowMessage(List.Text); //bbb ccc aaa

//排序
  List.Sort;
  ShowMessage(List.Text); //aaa bbb ccc

//倒排序
  List.CustomSort(DescCompareStrings); //调用排序函数
  ShowMessage(List.Text); //ccc bbb aaa

//假如:
  List.Sorted := True;
  List.Add('999');
  List.Add('000');
  List.Add('zzz');
  ShowMessage(List.Text); //000 999 aaa bbb ccc zzz
end;