Einzelnen Beitrag anzeigen

Benutzerbild von Luckie
Luckie

Registriert seit: 29. Mai 2002
37.621 Beiträge
 
Delphi 2006 Professional
 
#8

AW: Buchstabenhäufigkeit

  Alt 13. Feb 2017, 11:18
Hier die Erweiterung und ein paar Code Verschönerungen:

Delphi-Quellcode:
unit Unit6;

interface

uses
  SysUtils;

type TCharRecord = record
    FChar: AnsiChar;
    FCharCnt: Cardinal;
    FPercentage: Extended;
end;

var
  CharRecordArray: array [1..26] of TCharRecord;

procedure CntCharOccurrence(Text: AnsiString);

implementation

procedure CntCharOccurrence(Text: AnsiString);
var
  i: Integer;
  MyOrdChar: Integer;
  s: AnsiString;
  BaseValue: Integer;
  Percentage: Extended;
begin
  // Init array
  for i := Low(CharRecordArray) to High(CharRecordArray) do
  begin
    CharRecordArray[i].FChar := Chr(i + 64);
    CharRecordArray[i].FCharCnt := 0;
    CharRecordArray[i].FPercentage := 0;
  end;
  // calcualte occurence
  s := AnsiUpperCase(Text);
  s := StringReplace(s, ' ', '', [rfReplaceAll]);
  for i := 1 to Length(s) do
  begin
    MyOrdChar := Ord(s[i]) - 64; // A = 1, B = 2, ...
    if (MyOrdChar in [1..26]) then
    begin
      CharRecordArray[MyOrdChar].FCharCnt := CharRecordArray[MyOrdChar].FCharCnt + 1;
    end;
  end;
  // calculate percentage
  BaseValue := Length(s);
  for i := Low(CharRecordArray) to High(CharRecordArray) do
  begin
    Percentage := CharRecordArray[i].FCharCnt / BaseValue * 100;
    CharRecordArray[i].FPercentage := Percentage;
  end;
end;

end.
Delphi-Quellcode:
procedure TForm5.btn1Click(Sender: TObject);
var
  i: Integer;
  s: AnsiString;
begin
  s := '';
  CntCharOccurrence(mmo1.Text);
  for i := Low(CharRecordArray) to High(CharRecordArray) do
  begin
    s := s + Format('%s: %d' + #9 + '(%2.2f%%)', [CharRecordArray[i].FChar, CharRecordArray[i].FCharCnt, CharRecordArray[i].FPercentage]) + #13#10;
  end;
  ShowMessage(s);
end;
Michael
Ein Teil meines Codes würde euch verunsichern.
  Mit Zitat antworten Zitat