2013-02-16 46 views
16

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

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”的第一次出现,但我不能似乎发现这样做的方法如前所述,我只能访问字符'@'。有没有一种方法来完成这样的任务。

+2

的[我怎么能替换另一个字符串中的一个子可能重复Haskell没有使用像MissingH这样的外部库?](http://stackoverflow.com/questions/14880299/how-can-i-replace-a-substring-of-a-string-with-another-in-haskell-without-使用) – 2013-02-16 08:54:06

+1

我想,这已经在这里讨论: http://stackoverflow.com/questions/14 880299/how-can-i-replace-a-substring-of-string-with-another-in-haskell-without-using – kaan 2013-02-16 08:54:11

+1

这实际上并不重复。另一个问题明确排除使用其他库,这是对这个问题的合理答案。 – 2013-02-20 16:34:45

回答

20

您可以使用Data.List.Utils取代,这是懒惰的,你可以处理大文件,有的像:

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

这一切!

一个可能的替换功能可能是

rep a b [email protected](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 
+11

或者,使用'split'包中的[Data.List.Split](http://hackage.haskell.org/packages/archive/split/0.2.1.1/doc/html/Data-List-Split.html)它是Haskell平台的一部分,定义'替换旧的new =插入新的。 splitOn old'。 – 2013-05-03 04:19:11

相关问题