How to improve multiple StringReplace calls?

筅森魡賤 提交于 2019-12-03 20:17:25

I guess, you have to split your string into a set of strings ( non-delimiters and delimiters(patterns) ) and then replace items in the array and then combine them back yet again. You would start with longer patterns and go to shorter ones (safety check against pattern-inside-pattern), then an extra run would be to make one-char-to-one-char substitutions (as they can be done in-place and would not require memory copying).

Double copy, and search scaling as O(Length(input)*Count(Delimiters)).

Something like this pseudocode draft (not implemented to the last dot, just for you to have the idea):

Since your patterns are short I think linear search would be okay, otherwise more optimized but complex algorithms would be needed: https://en.wikipedia.org/wiki/String_searching_algorithm#Algorithms_using_a_finite_set_of_patterns

Hash it to smaller functions as you see fit for ease of understanding/maintenance.

Type TReplaceItem = record (match, subst: string; position: integer);
var matches: array of TReplaceItem;

SetLength(matches, 3);
matches[0].match := '
'; // most long first;
  matches[0].subst := ''; 
matches[1].match := #$D#$A; // most long first;
  matches[1].subst := #8; 
matches[2].match := #34; // most long first;
  matches[2].subst := '\_/'; 

sb := TStringBuilder.Create( 2*Length(InputString) ); 
// or TList<String>, or iJclStringList of Jedi CodeLib, or TStringList... depending on performance and preferences
// Capacity parameter is for - warming up, pre-allocating memory that is "usually enough" 
try    

  NextLetterToParse := 1;
  for I := Low(matches) to high(matches) do
    matches[I].position := PosEx(matches[I].match, InputString, NextLetterToParse ); 

  While True do begin

     ClosestMatchIdx := -1;

     ClosestMatchPos := { minimal match[???].Position that is >= NextLetterToParse };
     ClosestMatchIdx := {index - that very [???] above - of the minimum, IF ANY, or remains -1}

     if ClosestMatchIdx < 0 {we have no more matches} then begin

      //dump ALL the remaining not-yet-parsed rest
        SB.Append( Copy( InputString, NextLetterToParse , Length(InputString));

      // exit stage1: splitting loop
        break;
     end;

     // dumping the before-any-next-delimiter part of not-parsed-yet tail of the input
     // there may be none - delimiters could go one after another
     if ClosestMatchPos > NextLetterToParse then
         SB.Append( Copy( InputString, NextLetterToParse, ClosestMatchPos-NextLetterToParse);

     // dumping the instead-of-delimiter pattern
     SB.Append( matches[ ClosestMatchIdx ].Subst );

     ShiftLength := (ClosestMatchPos - NextLetterToParse) + Length(matches[ ClosestMatchIdx ].Match); 
     // that extra part got already dumped now

     Inc( NextLetterToParse, ShiftLength);

     for I := Low(matches) to high(matches) do
       if matches[I].position < NextLetterToParse then
          matches[I].position := PosEx(matches[I].match, InputString, NextLetterToParse ); 
     // updating next closest positions for every affected delimiter,
     // those that were a bit too far to be affected ( usually all 
     // but the one being dumped) need not to be re-scanned 

  end; // next stage 1 loop iteration

Now we have a container/array/list/anything comprised of non-matched chunks and replaced patterns. Except for in-place one-char replacement. Time to merge and do one last scan.

Stage2String := SB.ToString();

finally 
  SB.Destroy; 
end;

for I := 1 to Length( Stage2String ) do
  case Stage2String[I] of
    #0: Stage2String[I] := #32;

    #10, #13: Stage2String[I] := #8;
    // BTW - ^M=#13=#$D sometimes can be met without trailing ^J=#10=#$A
    // that was the end-of-line char used in old Macintosh text files

    else ; // do nothing, let it stay as is
  end;

Result := Stage2String;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!