如何判断一个字符串是不是数字(执行速度快,代码少)?(50分)

  • 主题发起人 主题发起人 ndust
  • 开始时间 开始时间
N

ndust

Unregistered / Unconfirmed
GUEST, unregistred user!
如何判断一个字符串是不是数字(执行速度快,代码少)?
 
try
strtoint(s)
except
Showmessage('不是数字');
end;
 
给你一个函数,调试时会有错误提示,但直接执行可执行文件时不会有误。

Function IsNumeric(S:string):Boolean;
var
da:Double;
begin
Result:=False;
if S='' then exit;
try
Da:=StrtoFloat(S);
Result:=true;
except
exit;
end;
end;
 
function IsNum(const ANum:string):boolean;
begin
result:=true;
try
inttostr(ANum);
except
result:=false;
end
end;
 
用val函数
var i:integer;
f:extended;
begin
val(str,f,i) ;
if i=0 then
showmessage(str+'是数字')
else
showmessage(str+'不是数字')
end;
 
不赞成用这个方法,会触发异常
 
如果是小数呢?
是不是要StrToFloat()了,呵呵
shangshang的函数里应该是StrToInt()吧?
 
代码最少是用函数,但是建议还是用位操作来实现这种功能。
 
function isNum(str:string):boolean;
var i:integer;
begin
result := false;
if str='' then
exit;
result := true;
for i := 1 to length(str)
if str not in ['0'..'9'] then
begin
result := false;
break;
end;
end;
 
to 完颜兄:
会出发什么异常呀,我用啦很久没发现什么异常呀?
 
补充一点
function isNum(str:string):boolean;
var i:integer;
begin
result := false;
if str='' then
exit;
result := true;
for i := 1 to length(str)
if str not in ['.','0'..'9'] then //加个'.'
begin
result := false;
break;
end;
end;
 
楼上的兄弟也不对啊!如果有两个.呢?
 
function isNumber(const aStr: String): Boolean;
var
I : Integer;
S : String;
begin
Result := True;
I := 1;
S := Trim(aStr);
//判别符号
if S <> '' and (S[1] in ['+', '-']) then Inc(I);

//整数部分
while (I < Length(S)) and (S in ['0'..'9']) do
begin
Inc(I);
end;

//有小数点
if (I < Length(S)) and (S = '.') then
begin
Inc(I);
while (I < Length(S)) and (S in ['0'..'9']) do
begin
Inc(I);
end;

if I < Length(S) then Result := False;//遇到了非数字字符
end
else if (I < Length(S)) then //遇到了非数字字符
begin
Result := False;
end;
end;
 
如果真的还要考虑字符串里面会有两个.,则建议还是直接用函数进行try算啦!
 
trystrtoint(str)
 
tseug的方法我一直很喜欢,我加一个语句:
……
//有小数点
if (i < Length(s)) and (S = '.') then
begin
Inc(i);
if s = '.' then Dec(i); //加在这里,防止数字后两个小数点而不报错,如12..
while (i < Length(s)) and (s in ['0'..'9']) do
Inc(i);
if i < Length(s) then result := false; //遇到了非数字字符
end
……
 
奇怪,这么个问题也要写大段代段,DELPHI自带了一个函数,用它完全符合楼主的要求:

1、符合执行代码少(只有一个调用而已)
2、执行速度快(查看原码,汇编也)

function TryStrToFloat(const S: string; out Value: Extended): Boolean;
 
Allen的最简单
 
if (i < Length(s)) and (S = '.') then
begin
Inc(i);
if s = '.' then Dec(i); //加在这里,防止数字后两个小数点而不报错,如12..
while (i < Length(s)) and (s in ['0'..'9']) do
Inc(i);
if i < Length(s) then result := false; //遇到了非数字字符
end
 
你可以去找找关于正则表达式方面的资料,1般判断字符串都是采用这样的方法。
 
后退
顶部