Dephi: faster way to convert a "dirty" string to a number How can I make this code faster? the string can contain characters such as ", .?#" and possibly others.

Const Nums = ['0'..'9'];

function CleanNumber(s: String): Int64;
Var z: Cardinal;
begin
  for z := length(s) downto 1 do
   if not (s[z] in Nums) then Delete(s,z,1);
  if s = '' then
    Result := 0 else
    Result := StrToInt64(s);
end;
Don't over use set. It is faster when the items are discrete, but slower when the items are continuous. Although, the difference is very small in your case.

The problem here is that you use delete repeatedly. Each call moves (copies) a potentially large chuck of characters. This is inefficient because many characters are moved multiple times. For example, 5 in string 1 2 3 4 5 is moved 4 times.

Given that string in Delphi is mutable, it is better to copy individual characters:

function CleanNumber(s: String): Int64;
Var
  z, l: Cardinal;
begin
  l := 1;
  for z := 1 to length(s) do
    if (s[z] &gt;= '0') and (s[z] &lt;= '9') then
    begin
      s[l] := s[z];
      inc(l);
    end;
  SetLength(s, l - 1);

  if s = '' then
    Result := 0 else
    Result := StrToInt64(s);
end;


It can be further improved:

function CleanNumber(s: String): Int64;
Var
  z, l: Cardinal;
begin
  l := 1;
  while (l &lt;= length(s)) and (s[l] &gt;= '0') and (s[l] &lt;= '9') do
    inc(l);       // Scan for the first non-numeric char

  for z := l + 1 to length(s) do  // Start from l + 1
    if (s[z] &gt;= '0') and (s[z] &lt;= '9') then
    begin
      s[l] := s[z];
      inc(l);
    end;

  if l = 1 then Result := 0 else
  begin
    SetLength(s, l - 1);
    Result := StrToInt64(s);
  end;
end;


Note: code not tested.