![](/img/trans.png)
[英]Haskell - Capitalize the first letter of each word in a string without losing white spaces
[英]How to delete spaces in string and write first letter uppercase?
我試圖用 foldr 刪除單詞之間的每個空格和大寫單詞的每個字母。
我已經用 map 試過了:
deleteSpaces:: String -> String
deleteSpaces word = (filter(not . isSpace) .unwords . map (\(x:xs) -> (toUpper x):xs) . words) word
有用。
但是使用 foldr 我總是會出錯:
deleteSpacesF :: String -> String
deleteSpacesF word = (filter(not . isSpace) . unwords . foldr (\(x:xs) acc -> (toUpper x) : xs : acc) [] . words) word
我也試過(\x acc -> (toUpper (head x)):(tail x):acc)
錯誤是:
• 無法將類型“Char”與“[Char]”匹配 預期:字符串 實際:Char • 在“(:)”的第一個參數中,即“(toUpper x)” 在表達式中:(toUpper x): xs :acc 在'foldr'的第一個參數中,即'(\(x:xs)acc -> (toUpper x):xs:acc)'
x
是一個Char
,而不是一個String
,所以head x
和tail x
沒有意義。 你使用x
作為頭部, xs
作為尾部,所以。
因此它看起來像:
deleteSpacesF :: String -> String
deleteSpacesF = concat . foldr (\(x:xs) -> ((toUpper x : xs) :)) [] . words
你也可以省略concat
:
deleteSpacesF :: String -> String
deleteSpacesF = foldr (\(x:xs) -> (toUpper x :) . (xs ++)) [] . words
你可以這樣做:
process = concat . map cap . words
where
cap [] = []
cap (x:xs) = (toUpper x):xs
這定義了一個 helper function 來將第一個字母大寫,然后可以將其映射到從拆分原始字符串派生的每個單詞上。
請注意, words
還將制表符和換行符與常規空格一起視為分隔符,因此如果您只關心空格字符,則可能需要修改它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.