如何修剪字符串开头和结尾的空格?
trim " abc "
=>
"abc"
编辑:
好吧,让我说得更清楚一些。我不明白字符串文字的处理方式与字符串有何不同。
我想这样做:
import qualified Data.Text as T
let s :: String = " abc "
in T.strip s
这在 Haskell 中可能吗?我正在使用 -XOverloadedStrings 但这似乎只适用于文字。
最佳答案
如果您有严重的文本处理需求,请使用 hackage 中的 text
包:
> :set -XOverloadedStrings
> import Data.Text
> strip " abc "
"abc"
如果你太顽固而无法使用text
并且不喜欢反向方法的低效率,那么也许(我的意思是可能)像下面这样的东西会更有效:
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 .."
我写这篇文章的假设是空格的长度是最小的,所以你的 ++
和 reverse
的 O(n) 几乎不用担心。但我再次觉得有必要说,如果您确实关心性能,那么您根本不应该使用 String
- 移至 Text
。
编辑表达我的观点,快速 Criterion 基准测试告诉我(对于带有空格和 ~200 个前后空格的特别长的单词字符串)我的修剪需要 1.6 毫秒,使用反向修剪需要 3.5 毫秒,并且 Data.Text.strip
需要 0.0016 毫秒...
关于string - 在 Haskell 中,如何修剪字符串开头和结尾的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270324/