Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


1 Answers

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;
like image 194
Andreas Rejbrand Avatar answered Sep 12 '25 03:09

Andreas Rejbrand