How to check if two strings have the same number of words in Pascal

1 Answer

0 votes
program CheckEqualWordsProgram;

function CountWords(const S: string): Integer;
var
  i, WordCount: Integer;
  InWord: Boolean;
begin
  WordCount := 0;
  InWord := False;

  for i := 1 to Length(S) do
  begin
    if S[i] > ' ' then // Check for non-whitespace
    begin
      if not InWord then
      begin
        InWord := True;
        Inc(WordCount);
      end;
    end
    else
      InWord := False;
  end;

  CountWords := WordCount;
end;

var
  String1, String2: string;
  Words1, Words2: Integer;
begin
  String1 := 'c c++ pascal java c#';
  String2 := 'go rust php javascript swift';

  // Count words in each string
  Words1 := CountWords(String1);
  Words2 := CountWords(String2);

  // Compare the word counts
  if Words1 = Words2 then
    WriteLn('Both strings have the same number of words.')
  else
    WriteLn('The strings have a different number of words.');
end.



(*
run:

Both strings have the same number of words.

*)

 



answered Mar 22, 2025 by avibootz
...