将字符串拆分为交替单词(Scala) [英] Split String into alternating words (Scala)
本文介绍了将字符串拆分为交替单词(Scala)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个字符串拆分成交替的单词.总会有偶数.
I want to split a String into alternating words. There will always be an even number.
例如
val text = "this here is a test sentence"
应该转换为一些有序的集合类型,包含
should transform to some ordered collection type containing
"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))}
这给了我正确的结果作为两个数组.
which gives me the right results as two Arrays.
这能做得更优雅吗?
推荐答案
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)
这篇关于将字符串拆分为交替单词(Scala)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文