[英]Ruby: increment all integers in a string by +1
我正在尋找一種簡潔的方法來將字符串中的所有整數遞增+1並返回完整的字符串。
例如:
"1 plus 2 and 10 and 100"
需要成為
"2 plus 3 and 11 and 101"
我可以很容易地找到所有整數
"1 plus 2 and 10 and 100".scan(/\d+/)
但是我在這一點上陷入困境,試圖增加並將部件重新組合在一起。
提前致謝。
您可以使用String#gsub的塊形式 :
str = "1 plus 2 and 10 and 100".gsub(/\d+/) do |match|
match.to_i + 1
end
puts str
輸出:
2 plus 3 and 11 and 101
gsub
方法可以包含一個塊,因此您可以執行此操作
>> "1 plus 2 and 10 and 100".gsub(/\d+/){|x|x.to_i+1}
=> "2 plus 3 and 11 and 101"
你的正則表達式是它不會保留鏈中的原始字符串以便將它放回去。 我做的是使用空格分割它,使用w.to_i != 0
檢測哪些是單詞或整數(不計算0作為整數,你可能想要改進它),添加一個,然后加入它:
s = "1 plus 2 and 10 and 100"
s.split(" ").map{ |e| if (e.to_i != 0) then e.to_i+1 else e end }.join(" ")
=> "2 plus 3 and 11 and 101"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.