如何用两个条件分割字符串?

时间:2018-10-24 17:33:21

标签: haskell

所以基本上我想用两个条件来分割我的字符串,当空格或下一个字母不同时。

一个例子:

如果我有这个字符串,"AAA ADDD DD",我想分割成这个字符串,["AAA","A","DDD","DD"]

所以我编写了这段代码:

sliceIt :: String -> [String]
sliceIt xs = words xs

但是,仅当存在空白时,它才拆分初始字符串。 当不同的角色旁边有一个角色时,我又如何拆分? 递归可以解决这个问题吗?

2 个答案:

答案 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种情况:

  1. 如果head是一个空格,请忽略它。
  2. 否则,请使用尽可能多的相同字符,然后在字符串的其余部分调用函数。