[英]How to replace more than one element at the same time in a String (Haskell)
我想以2個列表為例;
find=["Hou","House","Mouse"]
repl=["Mou","Bird","House"]
所以當我給出這樣的文字時;
"The House with Mouse is big"
輸出應該是這個;
"The Mouse with House is big"
所以我寫了這個;
replace :: String->String->String->String
replace _ _ []=[]
replace find repl text
= if take(length find) text == find
then repl ++ replace find repl (drop (length find) text)
else [head text] ++ (replace find repl (tail text))
replaceMore ::[String]->[String]->String->String
replaceMore _ _ []=[]
replaceMore _ [] _ =[]
replaceMore [] _ _ =[]
replaceMore find repl text
= if (tail find) == [] || (tail repl)==[]
then text
else replaceMore (tail find)
(tail repl)
(replace (head find) (head repl) text)
它回來了
"The Mouse with Mouse is big"
所以它不像我想要的那樣工作,我認為問題在這里;
replaceMore _ _ []=[]
replaceMore _ [] _ =[]
replaceMore [] _ _ =[]
但我仍然不知道如何解決這個問題。任何想法?
我可能會給你一些關於工作算法的想法。
首先,您需要根據find
字符串將輸入String
划分為多個部分( [String]
)。 所以這個功能是
divideIntoParts :: [String] -> String -> [String]
有點像
divideIntoParts find "The House with Mouse is big"
給
["The ", "Hou", "se with ", "Mouse", " is big"]
因此,它從字符串中提取要替換的部分,但通過將其他部分保留在同一列表中來保留字母的順序。 天真的實現可能看起來像這樣
https://gist.github.com/Shekeen/5523749
接下來,您需要一個功能來掃描此列表並替換需要更換的部件。 簽名將是
replaceParts :: [String] -> [String] -> [String] -> String
哪個像
replaceParts find repl $ divideIntoParts find "The House with Mouse is big"
將會
"The Mouse with House is big"
所以你的完全replace
功能看起來像
replacePatterns :: [String] -> [String] -> String -> String
replacePatterns find repl = (replaceParts find repl) . (divideIntoParts find)
另外,您確實需要實現更快的子字符串搜索算法,並考慮用一個Data.Map
替換find
和repl
我可以看到兩個錯誤:
始終忽略find
和repl
的最終元素。 當tail find == []
或tail repl == []
時, replaceMore
返回text
; 應該在find == []
或repl == []
。
但它們應該被早期的方程式所捕獲
replaceMore _ [] _ =[] replaceMore [] _ _ =[]
哪個,你現在應該能看到,是錯的,應該是
replaceMore _ [] text = text replaceMore [] _ text = text
但那時的輸出就是
"The House with House is big"
還是錯的。 這是因為你正在構建replaceMore
out out replace
。 對於每個搜索詞,您搜索文本,找到后將其替換。 所以你用"Mou"
代替"Hou"
(所以"House"
被"Mouse"
代替); 然后你用"House"
取代"Mouse"
(意思是原來"House"
最終再次成為"House"
)。
相反,您應該搜索一次文本,在推進文本之前查找某個位置的每個搜索詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.