2013-02-16 89 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

相關問題