21

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 in the my code below

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 

I want to find the first occurrence of the string "@title", but i cant seem to find a method to do so as mentioned before, i can only access the char '@'. Is there a method for doing such a task.

5

1 Answer 1

22

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
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, using Data.List.Split from the split package which is part of Haskell Platform, define replace old new = intercalate new . splitOn old.
A better option would be to use replace :: Text -> Text -> Text -> Text from the text package: hackage.haskell.org/package/text-1.2.3.0/docs/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.