You could do
function RemoveNonAlphaASCIIFromStart(const Str: AnsiString): AnsiString; const ALPHA = ['A'..'Z', 'a'..'z']; var i: Integer; firstIndex: integer; begin result := ''; firstIndex := 0; for i := 1 to length(Str) do if Str[i] in ALPHA then begin firstIndex := i; break; end; if firstIndex > 0 then result := Copy(Str, firstIndex, length(Str)); end;
or as a procedure
procedure RemoveNonAlphaASCIIFromStart(var Str: AnsiString); const ALPHA = ['A'..'Z', 'a'..'z']; var i: Integer; firstIndex: integer; begin firstIndex := 0; for i := 1 to length(Str) do if Str[i] in ALPHA then begin firstIndex := i; break; end; if firstIndex > 0 then Delete(Str, 1, firstIndex - 1) else Str := ''; end;
For more complex methods that also work with Unicode Delphi, see my answer to a similar question . [This removes all non-alpha characters from the string.]
So why is your algorithm not working? Well, that should work, and it works for me. But note that it can be written in a slightly more elegant form.
const ALPHA = ['A'..'Z', 'a'..'z']; while true do if (length(s) = 0) or (s[1] in ALPHA) then break else delete(s, 1, 1);
One problem, however, with the OP source code is that it will fail if s is an empty string. In fact, then s[1] does not exist. It will not work if s consists entirely of non-alpha characters (for example, '!"#ยค% ).
source share