Einzelnen Beitrag anzeigen

Rollo62

Registriert seit: 15. Mär 2007
3.901 Beiträge
 
Delphi 12 Athens
 
#2

AW: Doppelte Buchstaben aus String auslesen

  Alt 17. Mai 2019, 16:53
Lustiges Spiel, könnte man z.B. so machen mit einem TDictionary als Speicher für die Zeichen und deren Anzahl.
Das gibt dann auch gleich noch die Anzahl der beteiligten Zeichen aus.

Delphi-Quellcode:
unit Unit1;

interface

uses
  System.Generics.Collections
  , Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
   TCharsCount = TDictionary<Char,Integer>;

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FChars : TCharsCount;

    function Convert(const AInput: String): String;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}



procedure TForm1.FormCreate(Sender: TObject);
begin
    FChars := TCharsCount.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
    FChars.Free;
end;

function TForm1.Convert(const AInput : String) : String;
var
  I: Integer;
  LChar : Char;
  LCount: Integer;
  LSB: TStringBuilder;
begin

    LSB := TStringBuilder.Create;

    try
        for I := Low(AInput) to High(AInput) do
        begin
            LChar := AInput[I];

            if FChars.TryGetValue( LChar, LCount) then
            begin
                Inc( LCount );
                FChars.Items[LChar] := LCount;
            end
            else
            begin // take only 1. time
                LCount := 1;
                if FChars.TryAdd(LChar, LCount) then
                    LSB.Append( LChar );
            end;

        end;

    finally
        Result := LSB.ToString;

        LSB.Free;
    end;

end;


procedure TForm1.Button1Click(Sender: TObject);
var
    LKey: Char;
begin
    FChars.Clear;
    Memo1. Clear;

    Memo1.Lines.Append( Convert( Edit1.Text ) );

    for LKey in FChars.Keys do
        Memo1.Lines.Append( LKey + ' - ' + FChars.Items[LKey].ToString + ' Zeichen' );
end;


end.
  Mit Zitat antworten Zitat