scala - 拆分字符串并获取每个段的起始索引
问题描述
我正在尝试拆分一个字符串并获取我得到的每个“单词”的所有起始索引。
例如对于这样的字符串:
"Rabbit jumped over a fence and this Rabbit loves carrots"
如何拆分它以获取每个单词的索引?:
0,7,14,19,21,27,31,36,43,49
解决方案
你可以这样做
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)
推荐阅读
- java - 如何设置 Eclipse RCP 插件以使用 JOGL?
- ios - 变量在完成处理程序之外变为 nil
- c++ - 采用 lambda 的模板类的类型推导
- javascript - 打字稿错误#70006,类型引用任何
- sql-server - SCOPE_IDENTITY、@@IDENTITY 和 IDENT_CURRENT 返回 null
- python - 按住键重复功能
- angular - AmCharts XY 图表 - 如何在 Angular 中单击时弹出模式?
- excel - 运行宏后,如何按升序对该 excel 列中的金额进行排序?
- windows - 安装 GYM openAI win 10/7
- sql - 基于从另一个数据点中排除来查找数据点的 SQL 查询