简体   繁体   English

Haskell - 使用递归替换字符串中的 substring(在我的例子中不允许使用函数 take 和 drop)

[英]Haskell - Replace substring in a string using recursion(functions take and drop are not allowed in my case)

I need to Replace one line in the sentence with another for example “qwer sder” “er” “ol” “qwol sdol”.我需要将句子中的一行替换为另一行,例如“qwer sder”“er”“ol”“qwol sdol”。 I managed to do something similar replacing one char with another我设法做了类似的事情,用另一个字符替换了一个字符

replace :: Char -> Char -> String -> String
replace _ _ "" = ""
replace x y (c:cs) = if c == x then y : replace x y cs else c : replace x y cs

But have no idea how to do that with strings (not chars).但是不知道如何使用字符串(不是字符)来做到这一点。

A naive algorithm can make use of the isPrefixOf:: [a] -> [a] -> Bool function to check if we should replace that element.天真的算法可以使用isPrefixOf:: [a] -> [a] -> Bool function 来检查我们是否应该替换该元素。

Such function thus looks like:这样的 function 看起来像:

replaceStr :: String -> String -> String -> String
replaceStr needle replacement = go
    where go "" = ""
          go xs@(x:xt)
              | isPrefixOf needle xs = …  -- (1)
              | otherwise = …  -- (2)
          nn = length needle

where I leave filling in the parts as an exercise.我留下填写部分作为练习。 In case the needle is a prefix of xs , one should drop nn characters from the string xs and replace these with the replacement and then recurse on the rest of the string (1).如果needlexs的前缀,则应从字符串xs中删除nn个字符并将其替换为replacement项,然后递归到字符串 (1) 的 rest。 In case the needle is not a prefix of xs , then we yield x and recurse on the tail xt (2).如果needle不是xs的前缀,那么我们产生x并在尾部xt (2) 上递归。

This algorithm can take quadratic time: if the needle is for example n characters 'A' and the "haystack" is m characters 'A' , then it will take O(m×n) time.该算法可能需要二次方时间:例如,如果针是n 个字符'A'而“大海捞针”是m个字符'A' ,那么它将花费O(m×n)时间。

One can work with the Knuth-Morris-Pratt algorithm [wiki] to perform search in linear time.可以使用Knuth-Morris-Pratt算法 [wiki]在线性时间内执行搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM