How to replace a string with another in haskell

后端 未结 1 1235
-上瘾入骨i
-上瘾入骨i 2021-02-02 12:35

I want to replace a string from an input file with a different string. I was searching for a method but it seems i can only alter the string character by character. For example

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 12:39

    You can use Data.List.Utils replace, it's lazy and you can process a big file with some like:

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

    That's all!

    A possible replace function could be

    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 _ _ [] = []
    

    another smart way (from Data.String.Utils)

    replace :: Eq a => [a] -> [a] -> [a] -> [a]
    replace old new l = join new . split old $ l
    

    0 讨论(0)
提交回复
热议问题