【发布时间】:2011-05-02 12:08:19
【问题描述】:
德尔福 7
如何删除 delphi 字符串中的前导零?
例子:
00000004357816
function removeLeadingZeros(ValueStr: String): String
begin
result:=
end;
【问题讨论】:
德尔福 7
如何删除 delphi 字符串中的前导零?
例子:
00000004357816
function removeLeadingZeros(ValueStr: String): String
begin
result:=
end;
【问题讨论】:
从类似“000”的字符串中正确删除前导零的代码:
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;
【讨论】:
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;
根据您可能希望修剪空白的确切要求。因为问题中没有提到,所以我在这里没有这样做。
更新
我修复了 Serg 在此答案的原始版本中发现的错误。
【讨论】:
使用JEDI Code Library 执行此操作:
uses JclStrings;
var
S: string;
begin
S := StrTrimCharLeft('00000004357816', '0');
end.
【讨论】:
可能不是最快的,但它是单线 ;-)
function RemoveLeadingZeros(const aValue: String): String;
begin
Result := IntToStr(StrToIntDef(aValue,0));
end;
当然,仅适用于整数范围内的数字。
【讨论】:
在 2021 年寻找这个,我现在发现了一个更好的解决方案,即使用 TStringHelper 函数 TrimLeft,如下所示
myString := myString.TrimLeft(['0']);
有关文档http://docwiki.embarcadero.com/Libraries/Sydney/en/System.SysUtils.TStringHelper.TrimLeft的更多信息,请参见此处
【讨论】:
试试这个:
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;
【讨论】: