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
textpackage from hackage:If you’re too stubborn to use
textand don’t like the inefficiency of the reverse method then perhaps (and I mean MAYBE) something like the below will be more efficient:I wrote this on the assumption that the length of spaces would be minimal, so your O(n) of
++andreverseis 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 usingStringat all – move toText.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.striptakes 0.0016 ms…