如何将字符串拆分为长度为3的字符串列表?

时间:2017-05-25 17:16:31

标签: string haskell

遇到问题,如果我想拆分一个字符列表,例如" qwertyzxc" (9个元素)(['q','w','e','r','t','y','z','x','c'])到长度为3的字符串列表中。我该怎么办? 例如:

输入:['q','w','e','r','t','y','z','x','c'] 输出:[['q','w','e'],['r','t','y'],['z','x','c']]

谢谢,我已经坚持了很长一段时间

4 个答案:

答案 0 :(得分:3)

如果段长度固定为3,那么您可以通过模式匹配

进行如下操作
segment :: [a] -> [[a]]
segment []           = []
segment [x]          = [[x]]
segment [x,y]        = [[x,y]]
segment (x:y:z:rest) = [x,y,z] : segment rest

*Main> segment [1,2,3,4,5,6,7,8,9]
[[1,2,3],[4,5,6],[7,8,9]]

答案 1 :(得分:2)

或者您也可以试试这个,免费检查长度:

segment :: [a] -> [[a]]
segment [a,b,c,d,e,f,g,h,i] = [[a,b,c],[d,e,f],[g,h,i]]
segment           _         = error "the list hasn't 9 items"

然后你试试:

> segment [1,2,3,4,5,6,7,8,9]
[[1,2,3],[4,5,6],[7,8,9]]

> segment [1,2,3,4,5,6,7,8]
*** Exception: the list hasn't 9 items

答案 2 :(得分:2)

p3::[a] -> [[a]]
p3 [] = []
p3 l = take 3 l : (p3 $ drop 3 l)

您可能会注意到,您可以轻松将其转换为pN

的更通用版本

答案 3 :(得分:0)

使用Data.List.Split中的chunksOf

n. 'pronouns' m.在注释中引用了预先打包的答案,尽管需要安装package

import Data.List.Split (chunksOf)
chunksOf :: Int -> [e] -> [[e]]
--Sample Usage
chunksOf 3 "HelloWorld" == ["Hel","loW","orl","d"]

定义自定义功能,仅限前奏

我编写的此函数与chunksOf完全相同,但不需要安装任何软件包:

splitInto :: Int -> String -> [String]
splitInto n = foldl (f n) [""]
    where
        f :: Int -> [String] -> Char -> [String]
        f n s x
            | (n >) $ length $ last s   = init s ++ [last s ++ [x]]
            | otherwise                 = s ++ [[x]]

它可能已被优化为使用:而不是++,但是如果不考虑性能,则可以使用。此外,它可以泛化除字符串以外的所有内容。

相关问题