How to improve multiple StringReplace calls?

2020-06-23 08:34发布

问题:

I read files from customers and I need to process the read data and remove some unneeded characters. My function works, but I'm trying to improve the FixData function to improve speed/performance and maintainability.

Is it possible to replace multiple StringReplace calls with something that will only loop through data once and replace with whatever it needs to?

I can't find MultipleStringReplace or similar function.

MCVE:

function FixData(const vStr:string):string;
var i:integer;
begin
  Result:=vStr;

  // empty string
  if Result = #0 then Result := '';

  // fix just New line indicator
  if Result = #13#10 then  Result := #8;

  // remove 'end'/#0  characters
    if Pos(#0, Result) > 0 then
      for i := 1 to Length(Result) do
        if Result[i] = #0 then
          Result[i] := ' ';

    //  #$D#$A  -> #8
    if Pos(#$D#$A, Result) > 0 then
      Result := StringReplace(Result, #$D#$A, #8, [rfReplaceAll]);

    // remove &#xD
    if Pos('
', Result) > 0 then
      Result := StringReplace(Result, '
', '', [rfReplaceAll]);

    // #$A -> #8
    if Pos(#$A, Result) > 0 then
      Result := StringReplace(Result, #$A, #8, [rfReplaceAll]);

    // replace " with temp_replacement value
    if Pos(chr(34), Result) > 0 then
      Result := StringReplace(Result, chr(34), '\_/', [rfReplaceAll]);
end;

procedure TForm1.Button1Click(Sender: TObject);
var vStr,vFixedStr:string;
begin
  vStr:='testingmystr:"quotest" - '+#0+' substr 
 new line '#$A' 2nd line '#$D#$A' end of data';
  vFixedStr:=FixData(vStr);
end;

回答1:

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;