In Haskell, how do you trim whitespace from the beginning and end of a string?

前端 未结 12 1419
感情败类
感情败类 2021-01-01 08:45

How do you trim whitespace from the start and end of a string?

trim \"  abc \" 

=>

\"abc\"

Edit:

Ok, let me be a little cleare

12条回答
  •  死守一世寂寞
    2021-01-01 09:11

    I don't know anything about the runtime or efficiency but what about this:

    -- entirely input is to be trimmed
    trim :: String -> String
    trim = Prelude.filter (not . isSpace')
    
    -- just the left and the right side of the input is to be trimmed
    lrtrim :: String -> String
    lrtrim = \xs -> rtrim $ ltrim xs
      where
        ltrim = dropWhile (isSpace')
        rtrim xs
          | Prelude.null xs = []
          | otherwise = if isSpace' $ last xs
                        then rtrim $ init xs
                        else xs 
    
    -- returns True if input equals ' '
    isSpace' :: Char -> Bool
    isSpace' = \c -> (c == ' ')
    

    A solution without using any other module or library than the Prelude.

    Some tests:

    >lrtrim ""
    >""
    
    >lrtrim "       "
    >""
    
    >lrtrim "haskell       "
    >"haskell"
    
    >lrtrim "      haskell       "
    >"haskell"
    
    >lrtrim "     h  a  s k e   ll       "
    >"h  a  s k e   ll"
    

    It could be runtime O(n).

    But I actually don't know it because I don't know the runtimes of the functions last and init. ;)

提交回复
热议问题