program RemoveComments;
function StripComments(const S: string): string;
var
i: Integer;
OutStr: string;
begin
i := 1;
OutStr := '';
while i <= Length(S) do
begin
// Check for // comment
if (i < Length(S)) and (S[i] = '/') and (S[i+1] = '/') then
begin
Inc(i, 2);
while (i <= Length(S)) and (S[i] <> #10) do
Inc(i);
end
// Check for (* ... *) comment
else if (i < Length(S)) and (S[i] = '(') and (S[i+1] = '*') then
begin
Inc(i, 2);
while (i < Length(S)) and not ((S[i] = '*') and (S[i+1] = ')')) do
Inc(i);
if i < Length(S) then Inc(i, 2);
end
// Normal character
else
begin
OutStr := OutStr + S[i];
Inc(i);
end;
end;
StripComments := OutStr;
end;
var
Input, OutputStr: string;
begin
Input :=
'var x := 10; // single-line comment' + LineEnding +
'var y := 20; (* block comment *)' + LineEnding +
'var z := x + y; (* multi' + LineEnding +
'line comment *) writeln(z);';
OutputStr := StripComments(Input);
Writeln(OutputStr);
end.
(* run:
var x := 10;
var y := 20;
var z := x + y; writeln(z);
*)