字符串解析代码出错
动态分配数组如果多分配1位则不会出错,想问为什么
procedure TForm1.Button1Click(Sender: TObject);
var
n,i,j,k,m:integer;
ConditionName:array of string;
stemp:string;
begin
SetLength(ConditionName,3);
stemp:= 'Money Age Method0 ';
n:=Length(stemp);
for i := 1 to 3 do
ConditionName[i]:= ' ';
i:=1;j:=1;m:=1;
showmessage(inttostr(n));
while i <=n do
begin
if (stemp[i]= ' ') or (stemp[i]= '0 ') then
begin
while j <i do
begin
ConditionName[m]:=ConditionName[m]+stemp[j];
inc(j);
end;
inc(m);
inc(j);
end;
inc(i);
end;
showmessage(ConditionName[3]);
end;
[解决办法]
会出错的,动态分配的数据从0开始不是从1开始
上面的代码要不出错得改成:
procedure TForm1.Button1Click(Sender: TObject);
var
n,i,j,m:integer;
ConditionName:array of string;
stemp:string;
begin
SetLength(ConditionName,3);
stemp:= 'Money Age Method0 ';
n:=Length(stemp);
for i := 0 to 2 do
ConditionName[i]:= ' ';
i:=1;j:=1;m:=0;
showmessage(inttostr(n));
while i <=n do
begin
if (stemp[i]= ' ') or (stemp[i]= '0 ') then
begin
while j <i do
begin
ConditionName[m]:=ConditionName[m]+stemp[j];
inc(j);
end;
inc(m);
inc(j);
end;
inc(i);
end;
showmessage(ConditionName[2]);
end;
[解决办法]
何必这样呢, DELPHI里提供了TParser就可以用于解析, 实在不行还有正则表达式控件.
[解决办法]
用这个就行了:
TStringList;
把空格与 '0 '替换成你的分隔符。然后,折分下字符串就行了。
uses StrUtils;
var
sourcestr:string;
descstrList:tstrings;
sourcestr:= 'Money Age Method0 ';
StringReplace(sourcestr, ' ', '* ',rfReplaceAll);
StringReplace(sourcestr, '0 ', '* ',rfReplaceAll);
descstrlist:=tstringlist.create(nil);
descstrlist.DelimitedText:=sourcestr;
descstrlist.Delimiter:= '* ';
...
descstrlist.free;