You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell如何从字符串中按规则提取生成多个字符列表?

Haskell 按固定间隔提取多字符串实现

功能说明

输入原字符串与正整数n,生成n个字符串:第k个字符串由原字符串第k位、k+n位、k+2n位……位置的字符依次拼接得到。

最简实现

直接通过列表推导实现,逻辑清晰易读,适合短字符串场景:

splitN :: Int -> String -> [String]
splitN n s = [ [s !! idx | idx <- [off, off + n .. length s - 1]] | off <- [0 .. n - 1] ]

高性能优化实现

避免列表索引查找(!!操作对长列表性能较差),使用drop递归取字符,适合处理长字符串场景:

splitN :: Int -> String -> [String]
splitN n s
  | n <= 0    = []
  | otherwise = map takeStep [0 .. n - 1]
  where
    takeStep off = go (drop off s)
    go [] = []
    go (x:rest) = x : go (drop (n - 1) rest)

效果验证

以示例输入测试:

-- 测试输入:原字符串 "abcdefghi",n=3
splitN 3 "abcdefghi"
-- 输出:["adg","beh","cfi"]

兼容边界情况:若原字符串长度不足n的整数倍,子串会按实际可提取字符长度自动截断,不会抛出异常。

内容的提问来源于stack exchange,提问作者Rara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 22:15:03