首页 > 解决方案 > 拆分字符串并获取每个段的起始索引

问题描述

我正在尝试拆分一个字符串并获取我得到的每个“单词”的所有起始索引。

例如对于这样的字符串:

"Rabbit jumped over a fence and this Rabbit loves carrots"

如何拆分它以获取每个单词的索引?:

0,7,14,19,21,27,31,36,43,49

标签: scalaindexingsplit

解决方案


你可以这样做

val str="Rabbit jumped over a fence and this Rabbit loves carrots"
val indexArr=str.split(" ").scanLeft(0)((prev,next)=>prev+next.length+1).dropRight(1)

样本输出:

ndexArr: Array[Int] = Array(0, 7, 14, 19, 21, 27, 31, 36, 43, 49)

推荐阅读