Uprościć dane znajdujące się w listbox

0

Mam w listbox takie przykładowe dane:

1 1 1 2 3 4 2 1 1 1 1 1 2 2 2 2 1 1 2
1 1 1 2 3 4 2 1 1 1 1 1 2 2 2 2 6 6 6

a chciałbym uzyskać postać bardziej uproszczona a mianowicie aby uzyskac:

1 2 3 4 2 1 2 1 2
1 2 3 4 2 1 2 6

Jaka funkcję zastosować aby uzyskać wskazany efekt?

Zrobiłem to tak choć nieporagnie wygląda ten kod

procedure TForm1.Button1Click(Sender: TObject);
var
i, ii, iii, a, b : integer;
sl, sl1, sl2 : TStringList;
s1, s2, s3 : string;
begin
sl := TStringList.Create;
sl1 := TStringList.Create;
sl2 := TStringList.Create;

for ii := 0 to ListBox1.Items.Count -1  do
begin
sl1.Clear;
sl2.Clear;
ExtractStrings([' ',' '], [], PChar(ListBox1.Items[ii]),sl2);

for iii := 0 to sl2.Count -1 do
begin
sl2.Insert(iii,sl2[sl2.Count-1]);
sl2.Delete(sl2.Count-1);
end;

sl2.Insert(0,'');

for i := sl2.Count -1 downto 1 do
begin
 s1 := sl2[i];
 s2 := sl2[i-1];

 if s1 = s2 then inc(a);
 if s1 = s2  then sl.Text := sl2[i];
 if s1 <> s2 then sl.Text := sl2[i];
 
 if s1 <> s2 then a := 0;
 if s1 <> s2 then sl1.Add(sl[sl.Count-1]);

 if i = 1 then break;

 application.ProcessMessages;
end;

s3 := sl1.DelimitedText;

s3 := StringReplace(s3, ',', ' ', [rfReplaceAll]);
showmessage(s3);
end;

sl.free;
sl1.free;
sl2.free;
end;
0

Ten wątek to kolejny dowód na to, że danych nie trzyma się jedynie w komponentach; Gdybyś dane trzymał choćby w głupiej tablicy oraz tylko wyświetlałbyś je w komponencie, mógłbyś sobie skrócić macierze, wywalić/złączyć duplikaty, a następnie wyczyścić komponent i uzupełnić po wszystkim; A tak to teraz będą odchodzić kombinacje z parsowaniem łańcuchów;

Poniżej masz przykładową funkcję, która usuwa duplikaty, zawarta w testowej aplikacji konsolowej:

{$MODE OBJFPC}{$LONGSTRINGS ON}

  function RemoveDuplicates(const AValue: String): String;
  var
    chrPattern: Char;
    intCharIdx: Integer = 1;
  begin
    Result := '';

    while intCharIdx <= Length(AValue) do
    begin
      chrPattern := AValue[intCharIdx];
      Result += chrPattern;

      repeat
        Inc(intCharIdx);
      until (intCharIdx > Length(AValue)) or (AValue[intCharIdx] <> chrPattern);
    end;
  end;

const
  SAMPLE_VALUE = '1112342111112222112';
begin
  WriteLn('Input:  ', SAMPLE_VALUE);
  WriteLn('Output: ', RemoveDuplicates(SAMPLE_VALUE));
  ReadLn();
end.

Wynik działania powyższego programu:

Input:  1112342111112222112
Output: 123421212

Jak widać działa prawidłowo; Tę funkcję możesz sobie przekopiować do swojego programu oraz użyć tuż po usunięciu białych znaków funkcją StringReplace;

Co prawda kod zawiera elementy szczególne dla Free Pascala (np. operator += oraz inicjowanie wartości zmiennej lokalnej w jej deklaracji), jednak przystosowanie kodu dla Delphi nie powinno być dla Ciebie problemem.

1 użytkowników online, w tym zalogowanych: 0, gości: 1