Delphi 7
How do i remove leading zeros in a delphi string?
Example:
00000004357816
function removeLeadingZeros(ValueStr: String): String
begin
result:=
end;
Delphi 7
How do i remove leading zeros in a delphi string?
Example:
00000004357816
function removeLeadingZeros(ValueStr: String): String
begin
result:=
end;
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.
Copy(Value,i)
will compile with Delphi 7. Perhaps you should need to write Copy(Value,i,maxInt)
–
Doane 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;
0000.89
results in .89
but 0.89
would be better. So I think the line no. 7 could be changed to: while (I < L) and (S[I] = '0') and (S[I+1] = '0') do Inc(I); –
Luge 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.
Copy(Value,i)
will compile with Delphi 7. Perhaps you should need to write Copy(Value,i,maxInt)
–
Doane Use JEDI Code Library to do this:
uses JclStrings;
var
S: string;
begin
S := StrTrimCharLeft('00000004357816', '0');
end.
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.
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
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;
© 2022 - 2024 — McMap. All rights reserved.