![](/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.