diff --git a/src/Data/String/Utils.hs b/src/Data/String/Utils.hs index 846a679a..ff628e3c 100644 --- a/src/Data/String/Utils.hs +++ b/src/Data/String/Utils.hs @@ -36,7 +36,8 @@ module Data.String.Utils ) where import Data.List.Utils (startswith, endswith, join, split, replace) -import Data.Char (isAlpha, isAscii, isDigit) +import Data.Char (isAlpha, isAscii, isDigit, isLetter) +import qualified Data.Char as C import Data.Maybe (listToMaybe) import Text.Regex (mkRegex, splitRegex) @@ -96,3 +97,15 @@ escapeRe (x:xs) -- | Attempts to parse a value from the front of the string. maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads + + +-- | Convert a String to title case (upper case the first letter in every word.) +toTitle :: String -> String +toTitle = go True + where + go _ [] = [] + go convert (x:xs) + | convert && letter = C.toTitle x : go False xs + | letter = x : go False xs + | otherwise = x : go True xs + where letter = isLetter x diff --git a/testsrc/Strtest.hs b/testsrc/Strtest.hs index 399f441a..f09347e9 100644 --- a/testsrc/Strtest.hs +++ b/testsrc/Strtest.hs @@ -52,6 +52,17 @@ test_splitWs = ] +test_toTitle = + mapassertEqual "toTitle" toTitle + [ ("", "") + , ("a", "A") + , ("2", "2") + , (" ", " ") + , ("eerg ro", "Eerg Ro") + , ("asdf\t 5fert", "Asdf\t 5Fert") + ] + + test_escapeRe = map (\i -> TestLabel (show $ chr i) $ TestCase $ assertEqual [chr i] (Just []) (matchRegex (mkRegex $ escapeRe $ [chr i]) [chr i])) @@ -67,7 +78,8 @@ tests = TestList [TestLabel "lstrip" (TestList test_lstrip), TestLabel "rstrip" $ TestList test_rstrip, TestLabel "strip" $ TestList test_strip, TestLabel "splitWs" $ TestList test_splitWs, - TestLabel "escapeRe" $ TestList test_escapeRe + TestLabel "escapeRe" $ TestList test_escapeRe, + TestLabel "toTitle" $ TestList test_toTitle ]