如何改进多个StringReplace调用?
我从客户那里读取文件,需要处理读取的数据并删除一些不需要的字符。我的功能正常工作,但我正在尝试改进FixData功能,以提高速度/性能和可维护性 是否可以将多个StringReplace调用替换为只循环一次数据并替换为所需的任何调用? 我找不到MultipleStringReplace或类似的函数 MCVE:如何改进多个StringReplace调用?,string,delphi,delphi-xe7,String,Delphi,Delphi Xe7,我从客户那里读取文件,需要处理读取的数据并删除一些不需要的字符。我的功能正常工作,但我正在尝试改进FixData功能,以提高速度/性能和可维护性 是否可以将多个StringReplace调用替换为只循环一次数据并替换为所需的任何调用? 我找不到MultipleStringReplace或类似的函数 MCVE: function FixData(const vStr:string):string; var i:integer; begin Result:=vStr; // empty s
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;
我想,您必须将字符串拆分为一组字符串(非分隔符和分隔符(模式)),然后替换数组中的项,然后再次将它们合并。您可以从较长的模式开始,然后转到较短的模式(针对模式内部的模式进行安全检查),然后额外运行一次,以进行一个字符对一个字符的替换(因为它们可以就地完成,并且不需要内存复制) 双重复制,搜索比例为O(长度(输入)*计数(分隔符)) 类似于这个伪代码草案(没有实现到最后一点,只是为了让您有这个想法): 由于您的模式很短,我认为线性搜索可以,否则需要更优化但更复杂的算法: 将其散列为您认为合适的较小函数,以便于理解/维护
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
是否可以将多个StringReplace调用替换为只在数据中循环一次并替换为所需的任何调用?是的。是什么阻止你这么做的?分配一个输出字符串。循环输入字符串,将字符复制到输出字符串中。如果检测到需要替换的字符,请将其替换。也许使用正则表达式是更好的选择?@daryal,他提到了“速度/性能和可维护性”…@MikeTorrettinni最糟糕的部分是,当新旧字符的大小[模式不同,那么就需要进行昂贵的内存复制。事实上,这并不是什么新鲜事,这是任何类似数组的容器的教科书属性:随机访问和替换非常便宜,但插入/删除元素非常昂贵。因此,这通常是第一个性能优化-尽可能少地进行内存复制保持代码可读性。实际上,在我的代码片段中,我可以避免复制字符串块,而是生成“坐标”一次完成后要复制的数据块。这将预先分配准确的内存量,并减少
InputString
数据的一个内存副本。但这将使代码更难掌握。大多数每性能优化都将不同的逻辑阶段融合到相同的执行单元中,从而模糊了logic结构,使维护更加困难。相反,我可以将阶段分开,不重叠,代码在概念上更清晰,但在执行中优化程度较低。你说的是“速度/性能和可维护性”但这通常是一种折衷,一个非此即彼的选择,并感谢您的努力@Arioch'the,但这对我来说太复杂了,我不知道自己在做什么。因此,Sam z被证明适合我。Sam z函数更复杂,它“展开”为了清晰起见,我跳过了这个阶段:-)我建议您阅读一些关于函数式语言的内容,它们是比Delphi/C++/Java更高级的抽象语言,并且倾向于将过程想象为数据和转换管道(函数)。只是为了让您更灵活。或者是为了反射来自OmniThreads Delphi库的管道模式。“当您只有锤子时,您只会看到到处都是钉子”基本上,如果我们坐在一张桌子旁,用纸和铅笔,我可以向你展示移动的块和那些没有低层次细节的概念,所有这些多变量,你会看到它是多么简单…这就是我建议你读一些ba的另一个原因sic介绍FP语言,你看到我的代码中没有分支,你看到的实现不是很简单的想法…而且它看起来很复杂,但绝对不是…遗憾的是,通过复杂,我不知道如何填充缺少的部分。几乎,SB.Dispose->SB.Destroy/SB.Free/FreeAndNil(SB)
在Delphi for Windows中,在Delphi/LLVM中,您只需SB:=nil;
或退出程序,其中SB是本地变量。
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;