将字符串拆分为交替的单词(Scala)

2024-01-09

我想将一个字符串分割成交替的单词。总会有一个偶数。

e.g.

val text = "this here is a test sentence"

应该转换为某种有序集合类型,其中包含

"this", "is", "test"

and

"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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串拆分为交替的单词(Scala) 的相关文章

随机推荐