[英]Haskell how to remove excessive spaces in a String
嘗試創建一個 function 刪除字符串中的所有雙/三等空格(並將它們合並到一個空格中)
到目前為止,我已經能夠刪除雙倍空格,但不確定如何將 go 刪除大約三倍甚至更多。
即"ab c de"
-> "ab c de"
formatSpace :: String -> String
formatSpace [] = []
formatSpace (' ':' ':xs) = ' ': formatSpace xs
formatSpace (x:xs) = x: formatSpace xs
考慮過嘗試將所有空格變成“-”,然后將所有這些空格變成一個空格。 能夠移動和前導和尾隨空格,但不能這樣做
我會這樣做:
formatSpace :: String -> String
formatSpace = foldr go ""
where
go x acc = x:if x == ' ' then dropWhile (' ' ==) acc else acc
這是最大程度的惰性,並且不會創建任何不必要的中間數據結構。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.