Reputation: 1
var
characters : array of array of char;
procedure TForm1.Button1Click(Sender: TObject);
var
spaces : integer;
nolines : integer;
linecounter : integer;
charcounter : integer;
space : char;
begin
nolines := memo1.lines.count-1;
setlength(characters, nolines+1);
for linecounter := 0 to nolines do begin
setlength(characters[linecounter], length(memo1.lines[linecounter]));
end;
space := ' ';
spaces := 0;
for linecounter := 0 to nolines do begin
for charcounter := 0 to Length(characters[linecounter]) do begin
if characters[linecounter,charcounter] = space then
spaces := spaces +1;
end;
end;
memo2.Lines.add(inttostr(spaces));
end;
I want to count how often a space occurs in my memo1. I have put all the characters in an array for practice but whenever I input text and spaces in the Memo, the count of spaces always returns zero.
Upvotes: 0
Views: 924
Reputation: 613013
You don't need the array. You can count characters from the control directly:
function CharCount(Strings: TStrings; Character: Char): Integer;
var
Line: string;
C: Char;
begin
Result := 0;
for Line in Strings do
for C in Line do
if C = Character then
inc(Result);
end;
Then you can simply write
Memo2.Lines.Add(IntToStr(CharCount(Memo1.Lines, ' ')));
Looking at your code, it essentially works apart from the fact that you don't initialise the array. And you get the array bounds wrong, running off the end of the inner arrays.
One final comment. Your variable named nolines
is mis-named because it holds one fewer than the number of lines. You should put the number of lines in a variable names nolines
and loop from 0
to nolines-1
. A more idiomatic choice of name would be LineCount
.
Upvotes: 3