每n个字符分割一次字符串 [英] Split string every n characters

查看:493
本文介绍了每n个字符分割一次字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将字符串分成两个字符的惯用方式是什么?

What would be an idiomatic way to split a string into strings of 2 characters each?

示例:

"" -> [""]
"ab" -> ["ab"]
"abcd" -> ["ab", "cd"]

我们可以假设字符串的长度是2的倍数.

We can assume that the string has a length which is a multiple of 2.

我可以在此Java答案中使用正则表达式,但我希望找到一种更好的方法(即使用一种Kotlin的其他方法).

I could use a regex like in this Java answer but I was hoping to find a better way (i.e. using one of kotlin's additional methods).

推荐答案

发布Kotlin 1.2后,您可以使用kotlin-stdlib的chunked函数. .com/Kotlin/KEEP/blob/master/proposals/stdlib/window-sliding.md"rel =" noreferrer> KEEP-11 提案.示例:

Once Kotlin 1.2 is released, you can use the chunked function that is added to kotlin-stdlib by the KEEP-11 proposal. Example:

val chunked = myString.chunked(2)

您已经可以使用科特琳1.2 M2预发布.

在此之前,您可以使用以下代码实现相同的操作:

Until then, you can implement the same with this code:

fun String.chunked(size: Int): List<String> {
    val nChunks = length / size
    return (0 until nChunks).map { substring(it * size, (it + 1) * size) }
}

println("abcdef".chunked(2)) // [ab, cd, ef]

此实现删除了少于size元素的其余部分.您可以对其进行修改,也将余数也添加到结果中.

This implementation drops the remainder that is less than size elements. You can modify it do add the remainder to the result as well.

这篇关于每n个字符分割一次字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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