You are here

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

Submitted by Asif Nowaj, Last Modified on 2019-11-22

Below is the function, using which you can find out the number of occurrences of a certain character in a string in Delphi.
For instance, assume that you have the following string and would like to count the number of commas in it:
Str := 'A,B,C';
Then you would like to obtain 2 as the result. Use below function.

function CountCharInString(str: string; SearchChar: char): integer;
// DESC: Returns the number of times a character occurs in a string.
// PARAM: str - the string.
// PARAM: SearchChar - the character to count the occurrences of.
// RETURNS: The number of times SearchChar occurs in str.
  i: integer;
  Result := 0;
  for i := 1 to Length(str) do
    if str[i] = SearchChar then Inc(Result);

Discussion or Comment

If you have anything in mind to share, please bring it in the discussion forum here.