您的位置:首页 > 其它

如何从字符串中提取数值

2011-06-02 08:41 369 查看
如何从字符串中提取数值,比如从'-10(16Mn)'中提取10这个数值,当然在字符串中'-'后面
的数值长度不定,而( )中的字符串长度也不定。

来个循环比较看看,条件是:IN(0..9)
str := 'abc056'
s:='';
for i:=1 to length(str) do
begin
if str[i] in ['0'..'9'] then
s:=s+str[i];
end;
http://zhidao.baidu.com/question/210744264.html

pos 加for应该可以提取出来

var s1:string;
i:integer;
begin
s1:='-10(16Mn)';
i:=pos('-',s1);
s1:=copy(s1,i+1,length(s1)-i);
i:=pos('(',s1);
s1:=copy(s1,1,i-1);//这时s1中就是'10'这个字符串了
end;

terry_lzs的方法思路是对的,不过不必过滤负号.
Result := StrToInt(Copy(S, 1, Pos('(', S) - 1);

如果不知道是用'('分隔的话会麻烦些:

b := True;
while b do
try
X := StrToInt(S);
b := False;
except
S := Copy(S, 1, Length(S) - 1);
end;

第二个算法有点问题,改一下:

b := True;
while b do
try
X := StrToInt(S);
b := False;
except
if Length(S) = 0 then Break
else
S := Copy(S, 1, Length(S) - 1);
end;

var
ss:string;
i:integer;
begin
i:=pos('10','-10(16Mn)');
label1.Caption:=copy('-10(16Mn)',i,2);
end;

上面各位的方法都可以,但我想大家可能都忽视了一个从Pascal继承下来,但现在很少用
的函数Val,请看下面的程序

var
s: String;
Code: Integer;
Value: Real;
begin
s := 'ABc-10.22E2(a';
repeat
Val(s, Value, Code);
case Code of
0: //转换成功
ShowMessage(FloatToStr(Value));
1: //开头有非法字符
Delete(s, 1, 1);
else //末尾有非法字符
Delete(s, Code, Length(s));
end;
until (Code = 0) or (Length(s) = 0);
end;

这段程序的优点在于,它不但对于检测整数有效,检测浮点数同样有效。
http://www.itdelphi.com/delphibbs/doc/2001/524238.htm

多谢各位帮助
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: