본문 바로가기

프로그래밍/Delphi

TStringList를 이용한 문자열 중복 제거 처리

TStringList 객체를 이용한 간단한 문자열 중복 제거 처리


프로그램중 문자열을 많이 다루게 되는데 문자열 목록을 중복을 배제하고 관리해야 할 경우가 있다.

예를 들어 검색을 위한 색인어 추출시 중복이 배제 되어야 하며, 키워드 목록 등이다.

이때 TStringList 객체를 이용하여 쉽게 문자열 중복을 배제 시킬 수 있다.

처리 함수 제작

procedure RemoveDuplicates(const stringList : TStringList) ;
 var
   buffer: TStringList;
   cnt: Integer;
 begin
   stringList.Sort;
   buffer := TStringList.Create;
   try
     buffer.Sorted := True;
     buffer.Duplicates := dupIgnore;
     buffer.BeginUpdate;
     for cnt := 0 to stringList.Count - 1 do
       buffer.Add(stringList[cnt]) ;
     buffer.EndUpdate;
     stringList.Assign(buffer) ;
   finally
     FreeandNil(buffer) ;
   end;
 end;

처리 예

 var
   sl : TStringList;
   cnt : integer;
 begin
   Randomize;
   sl := TStringList.Create;
   try
     for cnt := 1 to 1000 do
       sl.Add(IntToStr(Random(2000))) ;
 
     ShowMessage('With duplicates: ' + #13#10 + IntToStr(sl.Count)) ;
 
     RemoveDuplicates(sl) ;
 
     ShowMessage('Without duplicates: ' + #13#10 + IntToStr(sl.Count)) ;
   finally
     sl.Free;
   end;
 end;
 
행복한 프로그래머가 되기를....