Search code examples
delphidelphi-xe2delphi-2010

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


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.


Solution

  • 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;