如何在ruby中找出每场比赛的起点 [英] How to find out the starting point for each match in ruby

查看:50
本文介绍了如何在ruby中找出每场比赛的起点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有以下字符串

string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "

我想要 o/p

"#Sachin|0|7;#Tendulkar|29|10;#Sachinn|63|7;"

我尝试了以下

 new_string = ""
 string.scan(/#\S+/).each{|match| new_string+="#{match}|#{string.index(match)}|#{match.length};"  }

这给了我

 "#Sachin|0|7;#Tendulkar|29|10;#Sachin|0|7;" 

那么我将如何获得每个子字符串的起始索引?

So how i will get the starting index of each sub-string?

推荐答案

这实际上是一项非常重要的任务,并且已经在关于 SO 的其他问题中进行了大量讨论.这是最常见的解决方案:

This is actually quite a non-trivial task, and has been discussed quite a bit in other questions on SO. This is the most common solution:

string = "#Sachin is Indian cricketer. #Tendulkar is right hand batsman. #Sachin has been honoured with the Padma Vibhushan award "
new_string = string.to_enum(:scan,/#\S+/i).inject(''){|s,m| s + "#{m}|#{$`.size}|#{m.length};"}

这篇关于如何在ruby中找出每场比赛的起点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆