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

前端 未结 12 1383
感情败类
感情败类 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:08

    This should be right about O(n), I believe:

    import Data.Char (isSpace)
    
    trim :: String -> String
    -- Trimming the front is easy. Use a helper for the end.
    trim = dropWhile isSpace . trim' []
      where
        trim' :: String -> String -> String
        -- When finding whitespace, put it in the space bin. When finding
        -- non-whitespace, include the binned whitespace and continue with an
        -- empty bin. When at the end, just throw away the bin.
        trim' _ [] = []
        trim' bin (a:as) | isSpace a = trim' (bin ++ [a]) as
                         | otherwise = bin ++ a : trim' [] as
    

提交回复
热议问题