Gerhard Potgieter

The Ultimate Kloon

During this week I saw a request on my favourite forums MyBroadband about some guy wanting some help in Delphi counting the ocurrance of a certain character in a string. So I quickly put a function together and thought I’d might as well share it with you guys.

function CountChars(const str: string; c: char): integer;
// Returns the number of times a character occurs in a string
var
p: PChar;
begin
Result := 0;
p := PChar(Pointer(str));
while p <> nil do begin
p := StrScan(p, c);
if p <> nil then begin
inc(Result);
inc(p);
end;
end;
end;

To use it simply call as follows: CountChars(thestring,thechar);

Where thestring is the string you want to search in and thechar the character you want to count.

Add A Comment

Subscribe to Gerhard Potgieter