加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 为什么我使用Mike Heydon的TStringBuilder类来获取访

发布时间:2020-12-15 09:39:56 所属栏目:大数据 来源:网络整理
导读:我使用 a TStringBuilder class从.Net移植到Delphi 7. 这是我的代码片段: procedure TForm1.btn1Click(Sender: TObject);const FILE_NAME = 'PATH TO A TEXT FILE';var sBuilder: TStringBuilder; I: Integer; fil: TStringList; sResult: string; randInt:
我使用 a TStringBuilder class从.Net移植到Delphi 7.

这是我的代码片段:

procedure TForm1.btn1Click(Sender: TObject);
const
  FILE_NAME = 'PATH TO A TEXT FILE';
var
  sBuilder: TStringBuilder;
  I: Integer;
  fil: TStringList;
  sResult: string;
  randInt: Integer;
begin
  randomize;
  sResult := '';
  for I := 1 to 100 do
  begin
    fil := TStringList.Create;
    try
      fil.LoadFromFile(FILE_NAME);

      randInt := Random(1024);

      sBuilder := TStringBuilder.Create(randInt);
      try
        sBuilder.Append(fil.Text);
        sResult := sBuilder.AsString;
      finally
        sBuilder.free;
      end;

      mmo1.Text := sResult;
    finally
      FreeAndNil(fil);
    end;
  end;
  showmessage ('DOne');
end;

我遇到了AV错误.当我创建大小倍数为1024的内存时,我可以缓解这个问题,但有时它仍然会发生.

难道我做错了什么?

解决方法

你的代码很好.您正在使用的TStringBuilder代码有问题.考虑这种方法:

procedure TStringBuilder.Append(const AString : string); 
var iLen : integer; 
begin 
  iLen := length(AString); 
  if iLen + FIndex > FBuffMax then _ExpandBuffer; 
  move(AString[1],FBuffer[FIndex],iLen); 
  inc(FIndex,iLen); 
end;

如果当前缓冲区大小的未来长度太长,则扩展缓冲区. _ExpandBuffer将缓冲区的大小加倍,但一旦完成,它就不会检查新的缓冲区大小是否足够.如果原始缓冲区大小为1024,并且您加载的文件是3 KB,那么将缓冲区大小加倍到2048仍然会使Append中的缓冲区太小,并且最终会覆盖1024个字节超过缓冲.

在Append中将if更改为while.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读