返回 ruby​​ 字符串中所有出现的字符的索引 [英] Return index of all occurrences of a character in a string in ruby

查看:42
本文介绍了返回 ruby​​ 字符串中所有出现的字符的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Ruby 将索引返回到字符串中所有出现的特定字符.示例字符串为 "a#asg#sdfg#d##",搜索 时预期返回为 [1,5,10,12,13]# 字符.以下代码可以完成这项工作,但必须有更简单的方法吗?

I am trying to return the index's to all occurrences of a specific character in a string using Ruby. A example string is "a#asg#sdfg#d##" and the expected return is [1,5,10,12,13] when searching for # characters. The following code does the job but there must be a simpler way of doing this?

def occurances (line)

  index = 0
  all_index = []

  line.each_byte do |x|
    if x == '#'[0] then
      all_index << index
    end
    index += 1
  end

  all_index
end

推荐答案

s = "a#asg#sdfg#d##"
a = (0 ... s.length).find_all { |i| s[i,1] == '#' }

这篇关于返回 ruby​​ 字符串中所有出现的字符的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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