How to check whether the letters of a word exist in a string (order doesn't matter) in Pascal

1 Answer

0 votes
program WordLettersInSentence;

{$mode objfpc}{$H+}

{
  Returns True if all letters from AWord can be formed
  using the letters available in ASentence.

  - Case-insensitive.
  - Ignores non-alphabetic characters.
  - Letter order is not important.
}
function ContainsWordLetters(const ASentence, AWord: string): Boolean;
var
  LetterCounts: array['a'..'z'] of Integer;
  Ch: Char;
  Index: Char;
begin
  FillChar(LetterCounts, SizeOf(LetterCounts), 0);

  { Count available letters in the sentence. }
  for Ch in LowerCase(ASentence) do
  begin
    if Ch in ['a'..'z'] then
      Inc(LetterCounts[Ch]);
  end;

  { Consume letters required by the word. }
  for Ch in LowerCase(AWord) do
  begin
    if not (Ch in ['a'..'z']) then
      Continue;

    Index := Ch;
    Dec(LetterCounts[Index]);

    if LetterCounts[Index] < 0 then
      Exit(False);
  end;

  Result := True;
end;

var
  Sentence: string;
  Word: string;
begin
  Sentence := 'Bright stars shine above calm valleys at night.';
  Word := 'satellite';

  if ContainsWordLetters(Sentence, Word) then
    WriteLn('True')
  else
    WriteLn('False');
end.



{
run:

True

}

 



answered Sep 26 by avibootz

Related questions

...