Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: Remove chars from string

I have a string containing letters, numbers and other chars.
I want to remove from that string all numbers, dots and commas

Before: 'Axis moving to new position - X-Pos: 5.4mm / Y-Pos: 3.5mm'
After: 'Axis moving to new position - X-Pos mm / Y-Pos mm'

Unfortunately string.replace() only replaces one character. So I need several lines.

How can I avoid writing every replacement line by line?

  sString := sString.Replace('0', '');
  sString := sString.Replace('1', '');
  sString := sString.Replace('2', '');
  sString := sString.Replace('3', '');
  sString := sString.Replace('3', '');
  ...
  sString := sString.Replace(':', '');
  sString := sString.Replace('.', '');
like image 396
Michael Hutter Avatar asked Dec 19 '25 02:12

Michael Hutter


1 Answers

Although the OP's own solution is fine, it is somewhat inefficient.

Just for completeness, here's a slightly more optimized version:

function RemoveCharsFromString(const AString, AChars: string): string;
begin
  SetLength(Result, AString.Length);
  var ActualLength := 0;
  for var i := 1 to AString.Length do
  begin
    if SomePredicate(AString[i]) then
    begin
      Inc(ActualLength);
      Result[ActualLength] := AString[i];
    end;
  end;
  SetLength(Result, ActualLength);
end;

The algorithm is independent of the particular predicate. In this case, the predicate is Pos(AString[i], AChars) = 0.

like image 90
Andreas Rejbrand Avatar answered Dec 21 '25 01:12

Andreas Rejbrand