如何在haskell中用另一个字符串替换一个字符串

2024-05-21

我想用不同的字符串替换输入文件中的字符串。我正在寻找一种方法,但似乎我只能逐个字符地更改字符串。例如在我下面的代码中

replace :: String -> String 
replace [] = [] 
replace (x:xs) = if x == '@' then 'y':replace xs --y is just a random char
                             else x:replace xs

searching :: String -> IO String
searching filename = do
    text <- readFile filename
    return(replace text)


main :: IO ()
main = do

  n <- searching "test.sf"
  writeFile "writefile.html" n 

我想找到字符串“@title”的第一次出现,但我似乎找不到前面提到的方法,我只能访问字符“@”。有没有一种方法可以完成这样的任务。


您可以使用数据.列表.实用程序 http://hackage.haskell.org/packages/archive/MissingH/0.18.6/doc/html/Data-List-Utils.html#v%3areplace替换,它很懒,您可以使用以下命令处理大文件:

main = getContents >>= putStr . replace "sourceString" "destinationString"

就这样!

可能的替换功能可以是

rep a b s@(x:xs) = if isPrefixOf a s

                     -- then, write 'b' and replace jumping 'a' substring
                     then b++rep a b (drop (length a) s)

                     -- then, write 'x' char and try to replace tail string
                     else x:rep a b xs

rep _ _ [] = []

另一种聪明的方式(来自Data.String.Utils)

replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace old new l = join new . split old $ l
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在haskell中用另一个字符串替换一个字符串 的相关文章

随机推荐