2Pascal-新时代的Pascal

 找回密码
 立即注册
搜索
热搜: fastreport
查看: 1563|回复: 2
打印 上一主题 下一主题

极速字符串替换函数[40秒变40毫秒](hq200306原创)

[复制链接]

3

主题

12

帖子

48

积分

新手上路

Rank: 1

积分
48
跳转到指定楼层
楼主
发表于 2015-12-31 10:28:42 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
京东购书支持本站
//此极速字符串替换函数为[盒子论坛hq200306兄]所作,在此感谢!亲测原本48秒的长文本替换操作,现在只要几十毫秒不到!

function PosX(const SubStr, Str: string; Offset: Integer): Integer;
var
  I, LIterCnt, L, J: Integer;
  PSubStr, PS: PChar;
begin
  L := Length(SubStr);
  { Calculate the number of possible iterations. Not valid if Offset < 1. }
  LIterCnt := Length(Str) - Offset - L + 1;

  { Only continue if the number of iterations is positive or zero (there is space to check) }
  if (Offset > 0) and (LIterCnt >= 0) and (L > 0) then
  begin
    PSubStr := PChar(SubStr);
    PS := PChar(Str);
    Inc(PS, Offset - 1);

    for I := 0 to LIterCnt do
    begin
      J := 0;
      while (J >= 0) and (J < L) do
      begin
        if UpCase(PS[I + J]) = UpCase(PSubStr[J]) then
          Inc(J)
        else
          J := -1;
      end;
      if J >= L then
        Exit(I + Offset);
    end;
  end;

  Result := 0;
end;

function StringReplaceEx(const st, oldSubstr, newSubStr: string): string;
var
  idx, len: Integer;
  iStart: Integer;
  sb: TStringBuilder;
begin
  len := Length(oldSubstr);
  iStart := 1;
  sb := TStringBuilder.Create;
  try
    repeat
      idx := posX(oldSubstr, st, iStart);
      if idx > 0 then
      begin
        sb.Append(Copy(st, iStart, idx - iStart));
        sb.Append(newSubStr);
        iStart := idx + len;
      end;
    until idx <= 0;
    sb.Append(Copy(st, iStart, length(st)));
    Result := sb.ToString;
  finally
    sb.Free;
  end;
end;

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
回复

使用道具 举报

3

主题

12

帖子

48

积分

新手上路

Rank: 1

积分
48
沙发
 楼主| 发表于 2015-12-31 10:29:57 | 只看该作者
京东数码购物支持本站
这里是和DELPHI自带的StringReplace函数比较。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|新时代Pascal论坛

GMT+8, 2024-4-29 20:01 , Processed in 0.058341 second(s), 24 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表