Autor Beitrag
antonc
Hält's aus hier
Beiträge: 7



BeitragVerfasst: Do 08.02.07 18:34 
Hallo,

wie kann ich zählen wie oft ein string ein bestimmtes Zeichen enthält?

MFG Anton
Chryzler
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 1097
Erhaltene Danke: 2



BeitragVerfasst: Do 08.02.07 18:38 
Du gehst jedes Zeichen im String einzeln durch, am besten mit einer For-Schleife, und zählst dann die Anzahl des bestimmten Zeichens.
F34r0fTh3D4rk
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 5284
Erhaltene Danke: 27

Win Vista (32), Win 7 (64)
Eclipse, SciTE, Lazarus
BeitragVerfasst: Do 08.02.07 20:54 
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
var
  anzahlen: array [0..255of integer;
  astr: string;
  i: integer;
begin
  for i := 1 to length(astr) do
    anzahlen[ord(astr[i])] := anzahlen[chr(astr[i])] + 1;
end;


ungetestet, aber sollte laufen, dann kannst du das so ausgeben (memo1 vorrausgesetzt):
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
var
  i: integer;
begin
  for i := 0 to 255 do
    memo1.lines.add('Das Zeichen ' + chr(i) + ' kommt ' + inttostr(anzahlen[i]) + ' mal vor'
end;


natürlich sind da auch viele nicht druckbare zeichen dabei, aber ich denke die bekommst du noch gefiltert, ist ja nur der grundansatz ;)

wenns nur um ein bestimmtes zeichen geht, reicht eine if abfrage:

ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
var
  i: integer;
  astr: string;
  count: integer;
begin
  for i := 1 to length(astr) do
    if astr[i] = 'a' then
      inc(count);
end;
Chryzler
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 1097
Erhaltene Danke: 2



BeitragVerfasst: Do 08.02.07 21:21 
user profile iconF34r0fTh3D4rk hat folgendes geschrieben:
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
var
  i: integer;
  astr: string;
  count: integer;
begin
  for i := 1 to length(astr) do
    if astr[i] = 'a' then
      inc(count);
end;

Also, ich würde die count-Variable vor der Schleife noch auf Null setzen...
JayEff
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 2971

Windows Vista Ultimate
D7 Enterprise
BeitragVerfasst: Do 08.02.07 21:33 
user profile iconChryzler hat folgendes geschrieben:
Also, ich würde die count-Variable vor der Schleife noch auf Null setzen...
Integervariablen werden immer mit 0 initialisiert, darum meckert auch der compiler nicht "[Warnung] blah könnte nicht initialisiert sein blah".

_________________
>+++[>+++[>++++++++<-]<-]<++++[>++++[>>>+++++++<<<-]<-]<<++
[>++[>++[>>++++<<-]<-]<-]>>>>>++++++++++++++++++.+++++++.>++.-.<<.>>--.<+++++..<+.