2013-06-19 151 views
1

說每場比賽的起點,我有以下字符串如何找出紅寶石

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;" 

那麼我將如何得到每個子串的起始索引?

回答

3

這實際上是相當不平凡的任務,並且在其他關於SO的問題上已經討論了很多。這是最常見的解決方案:

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};"} 
+1

+1並刪除了我的答案:)你可以通過注入string.to_enum(:scan,/#\ S +/i).inject(''){| s,m | s +「#{m} |#{$'.size} |#{m.length};」 } – trushkevich

+0

不知道它有助於閱讀,但無論如何它是相當難以辨認,所以我已經更新:)。謝謝。 –

1

下面是一個使用掃描:

offset = 0 
string.scan(/(#\S*)([^#]*)/).map{|m| v = "#{m[0]}|#{offset}|#{m[0].length};"; offset += m.join.length; v}.join 
#=> "#Sachin|0|7;#Tendulkar|29|10;#Sachin|63|7;"