Reputation: 1848
Delphi 7
How do i remove leading zeros in a delphi string?
Example:
00000004357816
function removeLeadingZeros(ValueStr: String): String
begin
result:=
end;
Upvotes: 15
Views: 12182
Reputation: 51
Searching for this in 2021 there is a much better solution that I found now and that is using the TStringHelper function TrimLeft as follows
myString := myString.TrimLeft(['0']);
see here for more on the documentation http://docwiki.embarcadero.com/Libraries/Sydney/en/System.SysUtils.TStringHelper.TrimLeft
Upvotes: 5
Reputation: 1
Try this:
function TFrmMain.removeLeadingZeros(const yyy: string): string;
var
xxx : string;
begin
xxx:=yyy;
while LeftStr(xxx,1) = '0' do
begin
Delete(xxx,1,1);
end;
Result:=xxx;
end;
Upvotes: 0
Reputation: 612954
function removeLeadingZeros(const Value: string): string;
var
i: Integer;
begin
for i := 1 to Length(Value) do
if Value[i]<>'0' then
begin
Result := Copy(Value, i, MaxInt);
exit;
end;
Result := '';
end;
Depending on the exact requirements you may wish to trim whitespace. I have not done that here since it was not mentioned in the question.
Update
I fixed the bug that Serg identified in the original version of this answer.
Upvotes: 12
Reputation: 896
Use JEDI Code Library to do this:
uses JclStrings;
var
S: string;
begin
S := StrTrimCharLeft('00000004357816', '0');
end.
Upvotes: 11
Reputation: 27493
Code that removes leading zeroes from '000'-like strings correctly:
function TrimLeadingZeros(const S: string): string;
var
I, L: Integer;
begin
L:= Length(S);
I:= 1;
while (I < L) and (S[I] = '0') do Inc(I);
Result:= Copy(S, I);
end;
Upvotes: 24
Reputation: 3079
Probably not the fastest one, but it's a one-liner ;-)
function RemoveLeadingZeros(const aValue: String): String;
begin
Result := IntToStr(StrToIntDef(aValue,0));
end;
Only works for numbers within the Integer range, of course.
Upvotes: 8