How to remove characters present in first string from the second string in Pascal

2 Answers

0 votes
program RemoveCharactersDemo;

{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TCharSet = set of Char;

function RemoveCharacters(const Source, CharsToRemove: string): string;
var
  Forbidden: TCharSet;
  Ch: Char;
begin
  Forbidden := [];

  { Build a lookup set of characters to remove }
  for Ch in CharsToRemove do
    Include(Forbidden, Ch);

  Result := '';

  { Keep only characters not present in the set }
  for Ch in Source do
    if not (Ch in Forbidden) then
      Result := Result + Ch;
end;

var
  First, Second: string;
begin
  First := 'programming language';
  Second := 'rogy';

  WriteLn('First : "', First, '"');
  WriteLn('Second: "', Second, '"');
  WriteLn('Result: "', RemoveCharacters(Second, First), '"');
end.



{
run:

First : "programming language"
Second: "rogy"
Result: "y"

}

 



answered Oct 3 by avibootz
0 votes
program RemoveCharactersDemo;

{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TCharSet = set of Char;

// For larger strings
function RemoveCharacters(const Source, CharsToRemove: string): string;
var
  Forbidden: TCharSet;
  Ch: Char;
  I: Integer;
begin
  Forbidden := [];

  for Ch in CharsToRemove do
    Include(Forbidden, Ch);

  SetLength(Result, Length(Source));
  I := 0;

  for Ch in Source do
    if not (Ch in Forbidden) then
    begin
      Inc(I);
      Result[I] := Ch;
    end;

  SetLength(Result, I);
end;

var
  First, Second: string;
begin
  First := 'programming language';
  Second := 'rogy';

  WriteLn('First : "', First, '"');
  WriteLn('Second: "', Second, '"');
  WriteLn('Result: "', RemoveCharacters(Second, First), '"');
end.



{
run:

First : "programming language"
Second: "rogy"
Result: "y"

}

 



answered Oct 3 by avibootz

Related questions

...