将字符串拆分为组 [英] Splitting string into groups

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

问题描述

我正在尝试将一个字符串分组"成段,我想这个例子会更简洁地解释它

I'm trying to 'group' a string into segments, I guess this example would explain it more succintly

scala> val str: String = "aaaabbcddeeeeeeffg"
... (do something)
res0: List("aaaa","bb","c","dd","eeeee","ff","g")

我可以想到几种以命令式风格执行此操作的方法(使用 vars 并逐步遍历字符串以查找组),但我想知道是否有更好的功能解决方案可以能达到吗?我一直在浏览 Scala API,但似乎没有适合我需要的东西.

I can thnk of a few ways to do this in an imperative style (with vars and stepping through the string to find groups) but I was wondering if any better functional solution could be attained? I've been looking through the Scala API but there doesn't seem to be something that fits my needs.

任何帮助将不胜感激

推荐答案

可以用span递归拆分字符串:

You can split the string recursively with span:

def s(x : String) : List[String] = if(x.size == 0) Nil else {
    val (l,r) = x.span(_ == x(0))
    l :: s(r) 
}

尾递归:

@annotation.tailrec def s(x : String, y : List[String] = Nil) : List[String] = {
    if(x.size == 0) y.reverse 
    else {
        val (l,r) = x.span(_ == x(0))
        s(r, l :: y)
    }
}

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

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