You are here

Get Number of Words within a string in Delphi

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

The following function returns the number of delimiter character and delimited words contained within the string. Here WideString is taken as parameter so that it remains compatible for Unicode string.


function StringGetNumberOfWords(s: WideString; DelimChar: WideChar): integer;
var
  i, WordStart: integer;
begin
  Result := 0;

  if s = '' then exit;

  WordStart := -1;
  for i := 1 to Length(s) do
  begin
    if s[i]  DelimChar then
    begin
      if WordStart = -1 then
        WordStart := i;
    end
    else
    begin
      if WordStart  -1 then
      begin
        Inc(Result);
        WordStart := -1;
      end;
    end;
  end;

  if s[Length(s)]  DelimChar then
    Inc(Result);
end;

Discussion or Comment

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

https://forum.everyething.com/delphi-f39/