如何从字符串的开头和结尾修剪空格?
trim " abc "
=>
"abc"
编辑:
好吧,让我说清楚一点。我不明白字符串文字与字符串的处理方式如此不同。
我想这样做:
import qualified Data.Text as T
let s :: String = " abc "
in T.strip s
这在 Haskell 中可行吗?我正在使用 -XOverloadedStrings 但这似乎只适用于文字。
如何从字符串的开头和结尾修剪空格?
trim " abc "
=>
"abc"
编辑:
好吧,让我说清楚一点。我不明白字符串文字与字符串的处理方式如此不同。
我想这样做:
import qualified Data.Text as T
let s :: String = " abc "
in T.strip s
这在 Haskell 中可行吗?我正在使用 -XOverloadedStrings 但这似乎只适用于文字。
如果您有严重的文本处理需求,请使用text
来自 hackage 的包:
> :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 .."
我在假设空间长度最小的情况下写了这个,所以你的 O(n)++
和reverse
是无关紧要的。但是我再次觉得有必要说,如果你真的关心性能,那么你根本不应该使用String
- 移至Text
.
编辑说明我的观点,一个快速的标准基准告诉我(对于一个特别长的带有空格和约 200 个前后空格的单词串)我的修剪需要 1.6 毫秒,使用反向修剪需要 3.5 毫秒,并且Data.Text.strip
需要 0.0016 毫秒。 .
来自:http ://en.wikipedia.org/wiki/Trim_(programming)#Haskell
import Data.Char (isSpace)
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
在提出这个问题之后(大约 2012 年) ,这Data.List
变得dropWhileEnd
容易多了:
trim = dropWhileEnd isSpace . dropWhile isSpace
效率低但易于理解并粘贴在需要的地方:
strip = lstrip . rstrip
lstrip = dropWhile (`elem` " \t")
rstrip = reverse . lstrip . reverse
当然,Data.Text 的性能更好。但是,正如前面提到的,用列表来做这件事很有趣。这是一个 rstrip 的字符串单遍(没有反向和 ++)并支持无限列表的版本:
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)
ps 对于无限列表,这将起作用:
List.length $ List.take n $ rstrip $ cycle "abc "
而且,由于显而易见的原因,这不会(将永远运行):
List.length $ List.take n $ rstrip $ 'a':(cycle " ")
您可以将Data.Text
'sstrip
与它的 un/packing 函数结合使用,以避免字符串重载:
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
测试它:
> let s = " hello "
> strip s
"hello"
> lstrip s
"hello "
> rstrip s
" hello"
如今,该MissingH
软件包附带了一个strip
功能:
import Data.String.Utils
myString = " foo bar "
-- strip :: String -> String
myTrimmedString = strip myString
-- myTrimmedString == "foo bar"
因此,如果在您的情况下来回转换String
没有Text
意义,您可以使用上面的函数。
我知道这是一篇旧帖子,但我没有看到实施良好旧的解决方案fold
。
首先使用dropWhile
. 然后,使用foldl'
一个简单的闭包,您可以一次分析字符串的其余部分,并基于该分析,将该信息参数传递给take
,而不需要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'
变量c
跟踪应该被吸收的组合空白和非空白,变量w
跟踪要被剥离的右侧空白。
测试运行:
print $ trim " a b c "
print $ trim " ab c "
print $ trim " abc "
print $ trim "abc"
print $ trim "a bc "
输出:
"a b c"
"ab c"
"abc"
"abc"
"a bc"
我相信这对 O(n) 应该是正确的:
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
按照其他人的建议,您可以避免使用以下方法反转字符串:
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
我对运行时或效率一无所知,但这又如何:
-- 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 == ' ')
除了 Prelude 之外,不使用任何其他模块或库的解决方案。
一些测试:
>lrtrim ""
>""
>lrtrim " "
>""
>lrtrim "haskell "
>"haskell"
>lrtrim " haskell "
>"haskell"
>lrtrim " h a s k e ll "
>"h a s k e ll"
它可能是运行时 O(n)。
但我实际上并不知道,因为我不知道函数 last 和 init 的运行时。;)
trim
如果您想在不导入任何精美包的情况下实现自己的功能。
import Data.Char (isSpace)
trimLeft :: String -> String
trimLeft = dropWhile isSpace
trimRight :: String -> String
trimRight = dropWhileEnd isSpace
trim :: String -> String
trim = trimRight . trimLeft
另一种(标准)解决方案
import System.Environment
import Data.Text
strip :: String -> IO String
strip = return . unpack . Data.Text.strip . pack
main = getLine >>= Main.strip >>= putStrLn