所以基本上我想用两个条件来分割我的字符串,当空格或下一个字母不同时。
一个例子:
如果我有这个字符串,"AAA ADDD DD"
,我想分割成这个字符串,["AAA","A","DDD","DD"]
所以我编写了这段代码:
sliceIt :: String -> [String]
sliceIt xs = words xs
但是,仅当存在空白时,它才拆分初始字符串。 当不同的角色旁边有一个角色时,我又如何拆分? 递归可以解决这个问题吗?
答案 0 :(得分:5)
因此,您想用words
分割,然后在每个分割中group
相等。您具有执行此操作的功能,
import Data.List
sliceIt :: String -> [String]
sliceIt s = concatMap group $ words s
sliceItPointFree = concatMap group . words -- Point free notation. Same but cooler
答案 1 :(得分:3)
split :: String -> [String]
split [] = []
split (' ':xs) = split xs
split (x:xs) = (takeWhile (== x) (x:xs)) : (split $ dropWhile (== x) (x:xs))
这是一个递归定义,其中有2种情况: