qinyi75 发表于 2011-4-2 09:07:56

字符串数组分割一个字符窜函数 求助

分割一个字符串如s,,df s.d+g,我用[',,','+',' ']作为分隔符ExtractStrings就不能用“,,”,好像只能单字符的。现在写了个函数用来分割,用能用了,但好像没地方释放StringList和tempslist,帮我看看怎么改
function SplitString(Source: string; Deli: Array of string): tstringList;
stdcall;
var
u, J, h, m: byte;
tstr: string;
Delis: Array of string;
StringList, tempslist: tstringList;
begin
StringList := tstringList.Create;
tempslist := tstringList.Create;
for u := 0 to High(Deli) do
begin
    tstr := '';
    J := Pos(Deli, Source);
    if J > 0 then
    begin
      h := length(Deli);
      setLength(Delis, High(Deli) - u);
      for m := 0 to High(Deli) - u - 1 do
      Delis := Deli;
      tstr := copy(Source, 1, J - 1);
      tempslist := SplitString(tstr, Delis);//用其他分割符分割这个字符
      if tempslist.Count = 0 then 。。没有分出来则原来的附进去
      tempslist.Add(tstr);
      for m := 0 to tempslist.Count - 1 do
      StringList.Add(tempslist);

      Source := copy(Source, J + h, length(Source) - J);//剩余的进行分割
      tempslist.Free;    //tempslist := tstringList.Create;
      tempslist:=nil;
      tempslist := SplitString(Source, Deli);//free nil了这么还能赋值???I基础差!
      if tempslist.Count = 0 then//没有分出来则原来的附进去
          tempslist.Add(Source);
      for J := 0 to tempslist.Count - 1 do
      begin
      StringList.Add(tempslist);
      end;
      Result := StringList;//返回结果直接退出,因为已经分完了,上面第一个FOR不需再执行下去
//StringList.Free;这里释放有问题
Exit;
    end;
end;
Result := StringList;//最后返回结果搞得好像不像递归了
//这里释放也不行
end;

深白海豚 发表于 2011-4-2 09:17:09

加班写程序中。。。。。 顺便给你写一个

//注意,不要在这个函数里面创建对象,应该是调用前创建
procedure SplitString(Const Source: string; Seps: Array of String; RetStringList: TStringList);
var ps: PChar;
    I, Index, Position: Integer;

    function GetPos(s: string; Seps: Array of String; var Index: Integer): Integer;
    var I, MinPos, tempPos: Integer;
    begin
      Result := 0;
      MinPos := $FFFFF; ////其实 这个SEPS最好事先按从小到大排序,这样可以写得更简单更效率,找到第一个就BREAK,不用在这里选出最小一个位置了
      for I := Low(Seps) to High(Seps) do
      begin
      tempPos := Pos(Seps, S);
      if tempPos > 0 then
      begin
          if tempPos < MinPos then
          begin
            MinPos := tempPos;
            Index := I;
          end;
      end;
      end;

      if MinPos <$FFFF then
      Result := MinPos;
end;

begin
ps := PChar(Source);//用指针更方便更效率
Position := GetPos(ps, Seps, Index); //这个函数可以优化 就是里面不用Pos这个函数, 如果不是大数据量的话 也无所谓
while Position > 0 do//没有必要用递归吧。。。。 简单的循环就可以了
begin
    RetStringList.Add(Copy(Ps, 1, Position - 1));
    Inc(Ps, Position + Length(Seps) - 1);
    Position := GetPos(ps, Seps, Index);
end;
if Ps^ <> #0 then
RetStringList.Add(Ps);

end;

procedure TForm1.Button1Click(Sender: TObject);
var Seps: Array of String;
    SS: TStringList;
begin
SS := TStringList.Create;
try
    SetLength(Seps, 2);
    Seps := ';;';
    Seps := '+';
    SplitString('+He+llo;;OhYes+dlkffj+', Seps, SS);
    ShowMessage(SS.Text);
finally
    SS.Free;
end;
end;

一个人在漂 发表于 2011-4-2 09:17:23

2楼的不错 学习了
页: [1]
查看完整版本: 字符串数组分割一个字符窜函数 求助