将字符串拆分为组

编程入门 行业动态 更新时间:2024-10-13 02:16:59
本文介绍了将字符串拆分为组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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) } }

更多推荐

将字符串拆分为组

本文发布于:2023-11-29 22:29:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!