我想用不同的字符串替换输入文件中的字符串.我正在寻找一种方法,但似乎我只能按字符改变字符串.例如,在下面的代码中
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
Run Code Online (Sandbox Code Playgroud)
我想找到第一次出现的字符串"@title",但我似乎找不到如前所述的方法,我只能访问字符'@'.有没有办法完成这样的任务.
jos*_*uan 21
您可以使用Data.List.Utils替换,它是懒惰的,您可以处理一个大文件,如:
main = getContents >>= putStr . replace "sourceString" "destinationString"
Run Code Online (Sandbox Code Playgroud)
就这样!
可能的替换功能可能是
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 _ _ [] = []
Run Code Online (Sandbox Code Playgroud)
另一种聪明的方式(来自Data.String.Utils)
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace old new l = join new . split old $ l
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8878 次 |
| 最近记录: |