How to check whether a user string contains any forbidden words from a list in Pascal

1 Answer

0 votes
program CheckForbidden;

const
  ForbiddenCount = 5;
  Forbidden: array[1..ForbiddenCount] of string = (
    'badword',
    'evil',
    'kill',
    'nasty',
    'terrible'
  );

function LowerCaseStr(s: string): string;
var
  i: integer;
begin
  for i := 1 to Length(s) do
    if (s[i] >= 'A') and (s[i] <= 'Z') then
      s[i] := Chr(Ord(s[i]) + 32);
  LowerCaseStr := s;
end;

function IsForbidden(const w: string): boolean;
var
  i: integer;
begin
  IsForbidden := False;
  for i := 1 to ForbiddenCount do
    if w = Forbidden[i] then
    begin
      IsForbidden := True;
      Exit;
    end;
end;

function ContainsForbidden(s: string): boolean;
var
  word: string;
  p: integer;
begin
  ContainsForbidden := False;
  s := LowerCaseStr(s);

  { Extract words separated by spaces }
  while s <> '' do
  begin
    p := Pos(' ', s);
    if p = 0 then
    begin
      word := s;
      s := '';
    end
    else
    begin
      word := Copy(s, 1, p - 1);
      Delete(s, 1, p);
      while (Length(s) > 0) and (s[1] = ' ') do
        Delete(s, 1, 1);
    end;

    if word <> '' then
      if IsForbidden(word) then
      begin
        ContainsForbidden := True;
        Exit;
      end;
  end;
end;

var
  input: string;

begin
  input := 'This text contains a badword inside';

  if ContainsForbidden(input) then
    Writeln('Forbidden word detected')
  else
    Writeln('No forbidden words found');
end.




(*
run:

Forbidden word detected

*)

 



answered Dec 26, 2025 by avibootz

Related questions

...