How to count number of occurrences of a certain char in string?

user1556433 picture user1556433 · Mar 8, 2013 · Viewed 30.6k times · Source

How can I count the number of occurrences of a certain character in a string in Delphi?

For instance, assume that I have the following string and would like to count the number of commas in it:

S := '1,2,3';

Then I would like to obtain 2 as the result.

Answer

Andreas Rejbrand picture Andreas Rejbrand · Mar 8, 2013

You can use this simple function:

function OccurrencesOfChar(const S: string; const C: char): integer;
var
  i: Integer;
begin
  result := 0;
  for i := 1 to Length(S) do
    if S[i] = C then
      inc(result);
end;