如何用haskell中的另一个替换字符串 [英] How to replace a string with another in haskell
问题描述
我想用不同的字符串替换输入文件中的字符串。我正在寻找一种方法,但似乎我只能改变字符的字符串。例如在下面的代码中:
replace :: String - >字符串
替换[] = []
替换(x:xs)= if x =='@'然后'y':替换xs --y只是一个随机字符
else x :替换xs
searching :: String - > IO字符串
搜索文件名= do
文本< - readFile文件名称
返回(替换文本)
main :: IO()
main = do
n< - 搜索test.sf
writeFilewritefile.htmln
我想查找字符串@title的第一个匹配项,但我似乎找不到前面提到的方法,我只能访问char'@' 。有没有一种方法来完成这样的任务。
您可以使用> Data.List.Utils 替换,它很懒,你可以用一些像处理一个大文件:
main = getContents>> = putStr。替换sourceStringdestinationString
可能的替换函数可能是
rep abs @(x:xs)= if isPrefixOf as
- 然后写'b'并替换跳跃的'a'子串
然后b ++ rep ab(drop(length a)s)
- 然后写'x'char并尝试替换尾字符串
else x:rep ab xs
rep _ _ [] = []
另一个聪明的方式(来自Data.String.Utils)
replace :: Eq a => [a] - > [a] - > [a] - > [a]
替换旧的新的l =加入新的。拆分旧$ l
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.
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
这篇关于如何用haskell中的另一个替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!