本帖最后由 beizidream 于 2013-07-03 09:46:04 编辑

解决方案 »

  1.   

    把起始/结束标志串存到byte数组,然后CompareMem对比stream,找出起始结束点,再copy到新stream不就行了
      

  2.   

    谢谢 ysai
    我想问下, 不同编码 起始标志需要处理吗,感觉utf-8的编码和gb23212的编码 起始/结束标志串的内容都会不同
      

  3.   

    比如起始串是"起始",你把它分别转成utf8和gb2312存到bytes数组,然后再分别查找一次不就可以了?
    这样还能区分出来你找出来的串是哪个编码
      

  4.   

    function GetContent(ms : TMemoryStream; starttag,endtag:string):TStringStream;
    var
      comparebytes : array of Byte;
      contentbytes : array of Byte;
      resultss : TStringStream;
      startpos,endpos, startlen,endlen, datasize : Integer;
      i,j : integer;
      isfind : Boolean;
    begin
      if (ms=nil) or (starttag='') or (endtag='') then exit;  startlen := Length(starttag);
      endlen := Length(endtag);
      datasize := Pred(ms.Size);
      resultss := TStringStream.Create(starttag, TEncoding.UTF8);
      SetLength(comparebytes, startlen+endlen);
      SetLength(contentbytes, startlen+endlen);
      isfind := False;  //把字符串内容放到bytes中
      resultss.Read(comparebytes, startlen);  //对比bytes
      j := Pred(datasize-startlen);
      for i := 0 to j do
      begin
        ms.Seek(i, soFromBeginning);
        ms.ReadBuffer(contentbytes, startlen);
        if CompareMem(@contentbytes, @comparebytes, startlen) then
        begin
          startpos := i+startlen;
          isfind := True;
          Break;
        end;
      end;
      //判断结果
      if not isfind then
      begin
        resultss.Clear;
        resultss.WriteString('');
        Result := resultss;
        exit;
      end else
      begin
        resultss.Clear;
        resultss.WriteString(endtag);
        isfind := False;
      end;  //把字符串内容放到bytes中
      resultss.Read(comparebytes, startlen);  //对比bytes
      for i := startpos to j do
      begin
        ms.Seek(i, soFromBeginning);
        ms.ReadBuffer(contentbytes, startlen);
        if CompareMem(@contentbytes, @comparebytes, startlen) then
        begin
          endpos := i;
          isfind := True;
          Break;
        end;
      end;
      //判断结果
      if not isfind then
      begin
        resultss.Clear;
        resultss.WriteString('');
        Result := resultss;
        exit;
      end else
      begin
        resultss.Clear;
        SetLength(contentbytes, endpos-startpos);
        ms.Seek(startpos, soFromBeginning);
        ms.ReadBuffer(contentbytes, endpos-startpos);
        resultss.Read(contentbytes, endpos-startpos);
        Result := resultss;
      end;
    end;
    写了一个函数,但是有不少错误,求帮忙看看