Mastodon
Programmierung

Strip Comments from String

[code lang=”delphi”]type
STRIP_STATES = ( SS_NORMA, SS_BRACE, SS_PAREN, SS_LITER );

function SCFS( const S : string; var SS : STRIP_STATES ): string;
// strip comments from string
var
I : integer;
begin
Result := ”;
I := 1;
while I <= Length( S ) do begin case SS of SS_NORMA : case S[ I ] of '{' : if ( I < Length( S ) ) and ( S[ I + 1 ] = '$' ) then Result := Result + S[ I ] else SS := SS_BRACE; '(' : if ( I < Length( S ) ) and ( S[ I + 1 ] = '*' ) then begin if ( I < Length( S ) - 1 ) and ( S[ I + 2 ] = '$' ) then Result := Result + S[ I ] else begin SS := SS_PAREN; Inc( I ); end; end else Result := Result + S[ I ]; '/' : if ( I < Length( S ) ) and ( S[ I + 1 ] = '/' ) then Exit else Result := Result + S[ I ]; '''' : begin SS := SS_LITER; Result := Result + S[ I ]; end; else Result := Result + S[ I ]; end; SS_BRACE : case S[ I ] of '}' : SS := SS_NORMA; end; SS_PAREN : case S[ I ] of '*' : if ( I < Length( S ) ) and ( S[ I + 1 ] = ')' ) then begin SS := SS_NORMA; Inc( I ); end; end; SS_LITER : case S[ I ] of '''' : begin SS := SS_NORMA; Result := Result + S[ I ]; end; else Result := Result + S[ I ]; end; end; // case SS of Inc( I ); end; // while I <= Length( S ) do begin end; // SCFS procedure STRIP_COMMENTS( slIN, slOUT : TStringList; EMPTY_LINES : boolean = false; // True - to preserve empty lines LEFT_TRIM : boolean = false; // True - to strip indentation RIGHT_TRIM : boolean = true ); // False - to preserve right white spaces // strips Object Pascal's comments // slIN - input, slOUT - output var I : integer; STRIP_STATE : STRIP_STATES; S : string; begin STRIP_STATE := SS_NORMA; for I := 0 to slIN.Count - 1 do begin S := SCFS( slIN[ I ], STRIP_STATE ); if LEFT_TRIM then S := TrimLeft( S ); if RIGHT_TRIM then S := TrimRight( S ); if EMPTY_LINES or ( Length( Trim( S )) > 0 ) then slOUT.Append( S );
end;
end; // STRIP_COMMENTS
[/code]

[tags]Delphi, Strings[/tags]

0 Kommentare zu “Strip Comments from String

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht.