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 
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;
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.
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.