簡體   English   中英

從 Haskell 中的字符串替換子字符串

[英]Replace a substring from a string in Haskell

我有以下字符串"not really//" ,我想編寫一個函數,用兩個點".."替換每兩個斜杠"//" ".."

我想過使用地圖,但后來我會遍歷字符並且不知道斜線后面是否會跟另一個斜線。 任何線索如何做到這一點? (沒有正則表達式)

我們可以使用Data.Text函數的replace :: Text -> Text -> Text -> Text Data.Text replace :: Text -> Text -> Text -> Text Data.Text replace :: Text -> Text -> Text -> Text Data.Text replace :: Text -> Text -> Text -> Text函數。 例如:

Prelude Data.Text> replace "//" ".." "not really//"
"not really.."

然而,我們在這里處理Text s。 如果這是一個問題,我們還可以使用pack :: String -> Textunpack :: Text -> StringStringText之間進行轉換。 所以我們可以定義一個函數:

{-# LANGUAGE OverloadedStrings #-}

import Data.Text(pack, unpack, replace)

replacedoubleslash :: String -> String
replacedoubleslash = unpack . replace "//" ".." . pack

但通常對於高效的字符串處理 - 無論是在速度還是內存方面 - 使用Text都比使用String更好。

顯式遞歸在這里看起來不錯:

replace :: String -> String
replace ('/':'/':xs) = '.' : '.' : replace xs
replace (x:xs)       = x : replace xs
replace ""           = ""

這不會擴展到長模式,但是對於替換“//”它應該可以正常工作。

如果你不想使用任何包,這就是我帶來的:

isHead':: String -> String -> String -> Bool
isHead' str [] ret = True
isHead' [] key  ret = False
isHead' (x:xs) (x':xs') ret = (x == x') && isHead' xs xs' ret

isHead:: String -> String ->  Bool
isHead  key str= isHead' str key key

remouveXelem:: Int ->[a] -> [a]
remouveXelem i a | i <= 0 = a
remouveXelem _ [] = [] 
remouveXelem i (x:xs) = remouveXelem (i - 1) xs  

replace :: String -> String -> String -> String
replace ori new [] = []
replace ori new s = if isHead ori s then
    new ++ replace ori new (remouveXelem (length ori) s)
    else head s : replace ori new (tail s)

替換“i”“a”“il etait une fois”=>“al etaat une foas”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM