How do you trim whitespace from the start and end of a string?
trim " abc "
=>
"abc"
Edit:
Ok, let me be a little clearer. I did not understand that string literals were treated so differently from Strings.
I would like to do this:
import qualified Data.Text as T
let s :: String = " abc "
in T.strip s
Is this possible in Haskell? I am using -XOverloadedStrings but that appears only to work for literals.
If you have serious text processing needs then use the text
package from hackage:
> :set -XOverloadedStrings
> import Data.Text
> strip " abc "
"abc"
If you're too stubborn to use text
and don't like the inefficiency of the reverse method then perhaps (and I mean MAYBE) something like the below will be more efficient:
import Data.Char
trim xs = dropSpaceTail "" $ dropWhile isSpace xs
dropSpaceTail maybeStuff "" = ""
dropSpaceTail maybeStuff (x:xs)
| isSpace x = dropSpaceTail (x:maybeStuff) xs
| null maybeStuff = x : dropSpaceTail "" xs
| otherwise = reverse maybeStuff ++ x : dropSpaceTail "" xs
> trim " hello this \t should trim ok.. .I think .. \t "
"hello this \t should trim ok.. .I think .."
I wrote this on the assumption that the length of spaces would be minimal, so your O(n) of ++
and reverse
is of little concern. But once again I feel the need to say that if you actually are concerned about the performance then you shouldn't be using String
at all - move to Text
.
EDIT making my point, a quick Criterion benchmark tells me that (for a particularly long string of words with spaces and ~200 pre and post spaces) my trim takes 1.6 ms, the trim using reverse takes 3.5ms, and Data.Text.strip
takes 0.0016 ms...
From: http://en.wikipedia.org/wiki/Trim_(programming)#Haskell
import Data.Char (isSpace)
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
After this question was asked (circa 2012) Data.List
got dropWhileEnd
making this a lot easier:
trim = dropWhileEnd isSpace . dropWhile isSpace
Inefficient but easy to understand and paste in where needed:
strip = lstrip . rstrip
lstrip = dropWhile (`elem` " \t")
rstrip = reverse . lstrip . reverse
For sure, Data.Text is better for performance. But, as was mentioned, it's just fun to do it with lists. Here is a version that rstrip's the string in single pass (without reverse and ++) and supports infinite lists:
rstrip :: String -> String
rstrip str = let (zs, f) = go str in if f then [] else zs
where
go [] = ([], True)
go (y:ys) =
if isSpace y then
let (zs, f) = go ys in (y:zs, f)
else
(y:(rstrip ys), False)
p.s. as for infinite lists, that will work:
List.length $ List.take n $ rstrip $ cycle "abc "
and, for obvious reason, that will not (will run forever):
List.length $ List.take n $ rstrip $ 'a':(cycle " ")
You can combine Data.Text
's strip
with it's un/packing functions to avoid having overloaded strings:
import qualified Data.Text as T
strip = T.unpack . T.strip . T.pack
lstrip = T.unpack . T.stripStart . T.pack
rstrip = T.unpack . T.stripEnd . T.pack
Testing it:
> let s = " hello "
> strip s
"hello"
> lstrip s
"hello "
> rstrip s
" hello"
Nowadays the MissingH
package ships with a strip
function:
import Data.String.Utils
myString = " foo bar "
-- strip :: String -> String
myTrimmedString = strip myString
-- myTrimmedString == "foo bar"
So if the conversion from String
to Text
and back does not make sense in your situation, you could use the function above.
I know this is an old post, but I saw no solutions that implemented good old fold
.
First strip the leading white-space using dropWhile
. Then, using foldl'
and a simple closure, you can analyze the rest of the string in one pass, and based on that analysis, pass that informative parameter to take
, without needing reverse
:
import Data.Char (isSpace)
import Data.List (foldl')
trim :: String -> String
trim s = let
s' = dropWhile isSpace s
trim' = foldl'
(\(c,w) x -> if isSpace x then (c,w+1)
else (c+w+1,0)) (0,0) s'
in
take (fst trim') s'
Variable c
keeps track of combined white and non white-space that should be absorbed, and variable w
keeps track of right side white-space to be stripped.
Test Runs:
print $ trim " a b c "
print $ trim " ab c "
print $ trim " abc "
print $ trim "abc"
print $ trim "a bc "
Output:
"a b c"
"ab c"
"abc"
"abc"
"a bc"
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
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. ;)
Along the lines of what other people have suggested, you can avoid having to reverse your string by using:
import Data.Char (isSpace)
dropFromTailWhile _ [] = []
dropFromTailWhile p item
| p (last items) = dropFromTailWhile p $ init items
| otherwise = items
trim :: String -> String
trim = dropFromTailWhile isSpace . dropWhile isSpace
Another (std) solution
import System.Environment
import Data.Text
strip :: String -> IO String
strip = return . unpack . Data.Text.strip . pack
main = getLine >>= Main.strip >>= putStrLn
来源:https://stackoverflow.com/questions/6270324/in-haskell-how-do-you-trim-whitespace-from-the-beginning-and-end-of-a-string