How to remove characters from a string (Views: 27)
Problem/Question/Abstract: We need a workable function that can strip embedded characters (single qoutes, double quotes, etc.,) from within string vars. Answer: Solve 1: Here is a general method to remove characters from a string: type TCharSet = set of Ansichar; procedure RemoveCharacters(var S: AnsiString; const characters: TCharset); var i: Integer; begin for i := Length(S) downto 1 do if S[i] in characters then delete(S, i, 1); end; In your case you would call it as: RemoveCharacters(aString, [' ']); There are certainly faster ways to implement this but unless you call the procedure some ten-thousand times in a loop I would not worry about that. Solve 2: function RemoveCharsFromString(const TheString: string; const CharsToRemove: array of Char): string; var i: Integer; begin Result := TheString; for i := Low(CharsToRemove) to High(CharsToRemove) do begin Result := StringReplace(Result, CharsToRemove[i], '', [rfReplaceAll]); end; end; Solve 3: type TSetOfChar = set of char; function RemoveCharsFromString(const TheString: string; const CharsToRemove: TSetOfChar): string; var i, j: Integer; begin SetLength(Result, length(TheString)); j := 0; for i := 1 to length(TheString) do begin if not (TheString[i] in CharsToRemove) then begin inc(j); Result[j] := TheString[i]; end; end; SetLength(Result, j); end; |