Home > Software engineering >  Delphi: Remove chars from string
Delphi: Remove chars from string

Time:05-02

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('.', '');

CodePudding user response:

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.

CodePudding user response:

uses System.SysUtils;

function RemoveCharsFromString(sFullString: string; sCharsToBeRemoved: string): string;
var
  splitted: TArray<String>;
begin
  splitted := sFullString.Split(sCharsToBeRemoved.ToCharArray());
  Result := string.Join('', splitted);
end;
  • Related