20

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

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”的第一次出现,但我似乎找不到前面提到的方法,我只能访问字符'@'。有没有办法完成这样的任务。

4

1 回答 1

22

你可以使用Data.List.Utils替换,它很懒,你可以处理一个大文件,比如:

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
于 2013-02-16T08:54:21.180 回答