假设我有以下字符串:
这里是55和55中的一些文字 其他一些文字仍然相同 句
字符串中有两个子串sentence
的实例。如何找到最接近子串55
?
我正在使用Ruby 1.9.2
答案 0 :(得分:4)
在标记上拆分字符串:
first, last = str.split("55")
与第二个的距离只需通过#index:
last_dist = last.index("sentence")
与第一个的距离稍微有些笨拙:
first_dist = first.reverse.index("sentence".reverse")
比较
result = first_dist < last_dist ? :first : :last
答案 1 :(得分:1)
str = "here is some text in a sentence 55 and some other text still in the same sentence"
t = str.index('55')
p [str.index('sentence', t), str.rindex('sentence', t)].min_by{|pos| (pos-t).abs}
答案 2 :(得分:1)
两个以上子串的更常见解决方案:
str = "text sub text text sub key text sub"
positions = []
last_pos = nil
key_pos = str.index('key')
while (last_pos = str.index('sub', (last_pos ? last_pos + 1 : 0)))
positions << last_pos
end
p positions.map{|p| (p-key_pos).abs}.min