function SplitStrToArray(const tString, tSplit: String): TStringList; //以后成为方法1,这也是《delphi超级猛料》中提到的算法 var t_Str, t_Item: WideString; t_Index, t_Len: Integer; t_StrList: TStringList; begin t_StrList := TStringList.Create(); t_Str := tString; t_Len := Length(tString); t_Index := pos(tSplit, t_Str); //语句1 if t_Index > 0 then begin while t_Index > 0 do begin t_Item := LeftStr(t_Str, t_Index - 1); t_Str := MidStr(t_Str, t_Index + 1, t_Len); t_Index := Pos(tSplit, t_Str); if Length(t_Item) > 0 then t_StrList.Add(t_Item); end; end; if Length(t_Str) > 0 then t_StrList.Add(t_Str); Result := t_StrList; end;
function SplitString(const source,ch:string):TStringList; //以后成为方法2; var temp:string; i:integer; begin result:=tstringlist.Create; temp:=source; i:=pos(ch,source); while i<>0 do begin result.Add(copy(temp,0,i-1)); delete(temp,1,i); i:=pos(ch,temp); end; result.Add(temp); end;
看上去两段代码都没有问题,然而,实际用这两段进行测试时:比如: s:=''''美国a,aab,中国,ddf''''; t:=SplitStrToArray(s,'''',''''); //t:=SplitString(s,'''',''''); for i:=0 to t.Count-1 do showmessage(t.Strings[i]);