加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

将字符串分割成交替单词(Scala)

发布时间:2020-12-16 09:17:47 所属栏目:安全 来源:网络整理
导读:我想将一个字符串分割成交替的单词.总是会有一个偶数. 例如 val text = "this here is a test sentence" 应该转换成一些有序的集合类型包含 "this","is","test" 和 "here","a","sentence" 我想出了 val (l1,l2) = text.split(" ").zipWithIndex.partition(_.
我想将一个字符串分割成交替的单词.总是会有一个偶数.

例如

val text = "this here is a test sentence"

应该转换成一些有序的集合类型包含

"this","is","test"

"here","a","sentence"

我想出了

val (l1,l2) = text.split(" ").zipWithIndex.partition(_._2 % 2 == 0) match {
  case (a,b) => (a.map(_._1),b.map(_._1))}

这给了我两个数组的正确结果.

这可以做得更优雅吗?

解决方法

scala> val s = "this here is a test sentence"
s: java.lang.String = this here is a test sentence

scala> val List(l1,l2) = s.split(" ").grouped(2).toList.transpose
l1: List[java.lang.String] = List(this,is,test)
l2: List[java.lang.String] = List(here,a,sentence)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读