2013-07-03 54 views
-1

我试着替换发现的文本递归,但我不能让它工作。 这将只更换1'a'字符每个'text'之前,但我想文本之前替换所有'a'字符德尔福递归函数替换字符串

//Declared recursive function 
function OneLine(s:WideString):WideString; 
begin 
s:=StringReplace(s,'atext', 'text', [rfReplaceAll]); 

if (Pos(Result,'atext')>0) then 
begin 
//XMLstring:=Result; 
s:=OneLine(XMLstring); 
end 
else 
begin 
Result:=XMLstring; 
end; 
end; 

//--Here begins program 
Var 
t:string 
Begin 

//exaple of text 
//we need replace all 'a' before 'text' only 
t:='aaHaaatextaaaatextHHaatextHHaaaa'; 

//call custom recursive function 
t:=OneLine(t); 

ShowMessage(t); 

End. 

我需要替换这样的:“aaHaaatextaaaatextHHaatextHHaaaa”

最终文本应该看起来像这一点: 'aaHtexttextHHtextHHaaaa'

+0

阅读“Pos”的文档,第一个参数是您要搜索的字符串。然后在同一行放置一个断点,并检查断点被命中时“结果”保存的内容。 –

+0

你应该使用一个和如果内部,你会很容易地解决你的问题;) –

+1

什么是XMLString?复制并粘贴您的真实代码。 –

回答

4

试试这个

function OneLine(const S, OldPattern, NewPattern: string):string; 
begin 
Result:=s; 
repeat 
    Result:=StringReplace(Result, OldPattern, NewPattern, [rfReplaceAll]); 
until Pos(OldPattern, Result)=0; 
end; 

,并使用像这样

OneLine('aaHaaatextaaaatextHHaatextHHaaaa','atext','text') 
+0

谢谢,但这不是递归函数。我已经尝试while循环,它的工作,但我尝试获得工作函数,将自己调用=递归功能 – Nafalem

+2

为什么你需要一个递归函数? – RRUZ

+0

因为...为什么不:) – Nafalem

2

您的递归逻辑是错误的,更不用说更复杂,那么它需要。试试这个:

function OneLine(const s: WideString): WideString; 
begin 
    if Pos(WideString('atext'), s) > 0 then 
    Result := OneLine(StringReplace(s, 'atext', 'text', [rfReplaceAll])) 
    else 
    Result := s; 
end; 

而且,你一定要明白,StringReplace()不支持WideString,不是吗?所以你在每一步都要做很多不必要的WideString-to-String-to-WideString数据转换。更改OneLine()采取并返回一个String代替它可以继续使用StringReplace()WideString转换只在初始调用点进行:

function OneLine(const s: String): String; 
begin 
    if Pos('atext', s) > 0 then 
    Result := OneLine(StringReplace(s, 'atext', 'text', [rfReplaceAll])) 
    else 
    Result := s; 
end; 

否则重新实现OneLine()停止使用StringReplace()干脆代替手动搜索 - 替换为仅使用WideString值。

0

感谢这帮了我很多。由于unicode的支持,我使用了widetring函数,但它似乎也是UTF-8的字符串函数(可能取决于Delphi的版本,我使用Turbo delhpi 7)。 我用它来格式化UTF-8编码的xml文件中的字符串。

function OneLineCDATA(const s: String): String; 
begin 
    if Pos(#9+'<![CDATA[', s) > 0 then 
    Result := OneLineCDATA(StringReplace(s, #9+'<![CDATA[', '<![CDATA[', [rfReplaceAll])) 
    else 
    if Pos(#13+#10+'<![CDATA[', s) > 0 then 
     Result := OneLineCDATA(StringReplace(s, #13+#10+'<![CDATA[', '<![CDATA[', [rfReplaceAll])) 
    else 
     if Pos(']]>'+#13+#10, s) > 0 then 
      Result := OneLineCDATA(StringReplace(s, ']]>'+#13+#10, ']]>', [rfReplaceAll])) 
     else 
      if Pos(']]>'+#9, s) > 0 then 
      Result := OneLineCDATA(StringReplace(s, ']]>'+#9, ']]>', [rfReplaceAll])) 
      else 
      Result := s; 

end; 
+0

疼痛等待。使用真正的XML库。 –