有了一个字符串比如:
sformat:='abc,15;x,5;y,9'
要的到的结果是15+5+9=29
我是这么做的
j:=0;
for i:=1 to length(sformat) do
begin
if sformat[i] in ['0'..'9'] then
j := j + strtoint(sformat[i]);
end;
这个只能把字符串中的小于10的加起来才是正确的。
他得出的结果是1+5+5+9=20。
怎么才能让两位或更多的位的数字作为一个整体加入?
sformat:='abc,15;x,5;y,9'
要的到的结果是15+5+9=29
我是这么做的
j:=0;
for i:=1 to length(sformat) do
begin
if sformat[i] in ['0'..'9'] then
j := j + strtoint(sformat[i]);
end;
这个只能把字符串中的小于10的加起来才是正确的。
他得出的结果是1+5+5+9=20。
怎么才能让两位或更多的位的数字作为一个整体加入?
tmpList : T
StringList;
iPos,iRet,i :integer;
begin
tmpList := TStringList;
iPos := pos(';',sFormat);
while iPos > 0 do
begin
tmpList.Append(copy(sFormat,1,iPos-1));
sFormat := copy(sFormat,iPos+1,length(sFormat)-iPos));
iPos := Pos(';',sFormat);
end;
if sFormat <> '' then
tmpList.Append(sFormat);
iRet := 0;
For i:=0 to tmpList.count-1 do
begin
iPos := Pos(',',tmplist.strings[i]);
if iPos > 0 then
iRet := iRet + strtoint(copy(tmpList.strings[i],iPos+1,length(tmpList.strings[i])-iPos);
end;
end;
2,把LIST里的相加
结果会是这样的1+5+5+9=20(错)同意 flyingkiller(大飞虫) (
var
i,j:integer;
cc:char;
str,str_num:string;begin
j:=0;
str:='abc,15;x,5;y19'
for i:=0 to length(str)+1 do
begin
cc:=str[i];
if (cc<='9') and (cc>='0') then
str_num:=str_num+cc
else
begin
try
j:=j+strtoint(str_num);
except
end;
str_num:='';
end;
end;
showmessage(inttostr(j));
end;刚测试过的,在编译的时候有类型转换错,但在exe中没有问题
1、先取出数字和‘;’号,这是办得到的,得到如下字符串:
sformat:='15;5;9'
2、再取出数字,方法是一次循环取一个数字,用数组保存:
第一次:
NUM[0]:=15;
第二次:
NUM[1]:=5;
。
3、最后数组值相加
var
sformat: string;
i,iSum: integer;
ObjArray: array of integer;//保存从字符串中提取的数
arrayCount: integer;//ObjArray数组中的元素个数
temp: string;
begin
arrayCount := 0;
temp := '';
iSum := 0;
sformat:='abc,15;x,5;y,9';
for i := 1 to length(sformat) do
begin
if sformat[i] in ['0'..'9'] then
begin
temp := temp + sformat[i];
if (i=length(sformat)) then
begin
inc(arrayCount);
setlength(ObjArray,arrayCount);
ObjArray[arrayCount-1] := StrToInt(temp);
end;
end
else
begin
if temp<>'' then
begin
inc(arrayCount);
setlength(ObjArray,arrayCount);
ObjArray[arrayCount-1] := StrToInt(temp);
temp := '';
end;
end;
end;
for i := 0 to High(ObjArray) do
begin
iSum := iSum + ObjArray[i];
end;
showmessage(IntToStr(iSum));
end;
这个方法只能处理整数,对于小数点的处理比较麻烦
a:integer;
begin
try
a:=toint(strings[i]);
except a:=0;
end;
end;)