Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way of stripping non alphanumeric characters from a string in Delphi7?

The characters allowed are A to Z, a to z, 0 to 9. The least amount of code or a single function would be best as the system is time critical on response to input.

like image 879
Johan Bresler Avatar asked Feb 22 '09 08:02

Johan Bresler


2 Answers

If I understand you correctly you could use a function like this:

function StripNonAlphaNumeric(const AValue: string): string;
var
  SrcPtr, DestPtr: PChar;
begin
  SrcPtr := PChar(AValue);
  SetLength(Result, Length(AValue));
  DestPtr := PChar(Result);
  while SrcPtr[0] <> #0 do begin
    if SrcPtr[0] in ['a'..'z', 'A'..'Z', '0'..'9'] then begin
      DestPtr[0] := SrcPtr[0];
      Inc(DestPtr);
    end;
    Inc(SrcPtr);
  end;
  SetLength(Result, DestPtr - PChar(Result));
end;

This will use PChar for highest speed (at the cost of less readability).

Edit: Re the comment by gabr about using DestPtr[0] instead of DestPtr^: This should compile to the same bytes anyway, but there are nice applications in similar code, where you need to look ahead. Suppose you would want to replace newlines, then you could do something like

function ReplaceNewlines(const AValue: string): string;
var
  SrcPtr, DestPtr: PChar;
begin
  SrcPtr := PChar(AValue);
  SetLength(Result, Length(AValue));
  DestPtr := PChar(Result);
  while SrcPtr[0] <> #0 do begin
    if (SrcPtr[0] = #13) and (SrcPtr[1] = #10) then begin
      DestPtr[0] := '\';
      DestPtr[1] := 't';
      Inc(SrcPtr);
      Inc(DestPtr);
    end else
      DestPtr[0] := SrcPtr[0];
    Inc(SrcPtr);
    Inc(DestPtr);
  end;
  SetLength(Result, DestPtr - PChar(Result));
end;

and therefore I don't usually use the ^.

like image 54
mghie Avatar answered Nov 15 '22 05:11

mghie


uses JclStrings;

  S := StrKeepChars('mystring', ['A'..'Z', 'a'..'z', '0'..'9']);
like image 42
Junior-RO Avatar answered Nov 15 '22 05:11

Junior-RO