Advertisement
WarPie90

Untitled

Dec 23rd, 2013
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.88 KB | None | 0 0
  1. function SubStrings(const Text: String; const Ptrn:String): TIntegerArray;
  2. var
  3.   hits,maxhits,h,q,i: Integer;
  4. begin
  5.   MaxHits := Length(Ptrn);
  6.   Hits := 1;
  7.   h := 0;
  8.   q := 1;
  9.   SetLength(Result, q);
  10.   for i:=1 to Length(Text) do
  11.   begin
  12.     if Text[i] = Ptrn[Hits] then
  13.     begin
  14.       Inc(Hits);
  15.       if (Hits > MaxHits) then
  16.       begin
  17.         if q <= h  then
  18.         begin
  19.           q := q+q;
  20.           SetLength(Result, q);
  21.         end;
  22.         Result[h] := (i - Hits) + 1;
  23.         Inc(h);
  24.         Hits := 1;
  25.       end;
  26.     end else
  27.       Hits := 1;
  28.   end;
  29.   SetLength(Result, h);
  30. end;
  31.  
  32.  
  33.  
  34. function StrReplace(Text, Ptrn, Rep: String; Flags:TReplaceFlags): String; Cdecl;
  35. var
  36.   Hi,HiPtrn,HiRep,i,j,k: Integer;
  37.   Prev,Curr:Integer;
  38.   Subs: TIntegerArray;
  39. begin
  40.   Hi := Length(Text);
  41.   if Hi = 0 then Exit;
  42.   case (rfIgnoreCase in flags) of
  43.     True: Subs := SubStrings(LowerCase(Text), LowerCase(Ptrn));
  44.     False:Subs := SubStrings(Text, Ptrn);
  45.   end;
  46.  
  47.   if Length(Subs) = 0 then
  48.     Exit(Copy(Text, 1,Hi));
  49.  
  50.   HiRep := Length(Rep);
  51.   HiPtrn := Length(Ptrn);
  52.  
  53.   SetLength(Result, Hi + (Length(Subs) * (HiRep-HiPtrn)));
  54.   k := 1;
  55.   Prev := 1;
  56.   case (rfReplaceAll in Flags) of
  57.   True:
  58.     begin
  59.       for i:=0 to High(Subs) do
  60.       begin
  61.         Curr := Subs[i];
  62.         j := (Curr-Prev) + 1;
  63.         Move(Text[Prev], Result[k], j);
  64.         k := k + j;
  65.         Move(Rep[1], Result[k], HiRep);
  66.         k := k+HiRep;
  67.         Prev := Curr + HiPtrn + 1;
  68.       end;
  69.       Move(Text[Prev], Result[k], Hi-Prev+1);
  70.     end;
  71.   False:
  72.     begin
  73.       Curr := Subs[0];
  74.       j := (Curr-Prev) + 1;
  75.       Move(Text[Prev], Result[k], j);
  76.       k := k + j;
  77.       Move(Rep[1], Result[k], HiRep);
  78.       k := k+HiRep;
  79.       Prev := Curr + HiPtrn + 1;
  80.       Move(Text[Prev], Result[k], Hi-Prev+1);
  81.       SetLength(Result, k+(Hi-Prev)+1);
  82.     end;
  83.   end;
  84. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement