将字符串拆分为相等的切片/块 [英] Split string into equal slices/chunks

查看:39
本文介绍了将字符串拆分为相等的切片/块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长度为 N 的字符串,我想将它分成等长的 L 部分(假设最后一部分可能更短).

I have a string of length N and I want to split it into equal parts of length L (assuming the last part might be shorter).

我想到的是:

string.split('').each_slice(L).map(&:join)

但这太长了(老实说也太丑了.)我是不是无法正确阅读文档,或者没有执行此任务的内置方法?

but this is toooooo long (and too ugly, to be honest.) Am I unable to read the documentation properly, or is there no built-in method to perform this task?

推荐答案

这个怎么样?

string.scan(/.{,#{L}}/)

这篇关于将字符串拆分为相等的切片/块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆