【问题标题】:Get the index of all characters in ruby获取ruby中所有字符的索引
【发布时间】:2015-10-05 18:08:16
【问题描述】:

我正在尝试获取具有重复字符的字符串的索引。但是如果我有相同的字符,它会不断返回该字符第一次出现的索引

    str = "sssaadd"

    str.each_char do |char|
       puts "index: #{str.index(char)}"
    end

Output:-
index: 0
index: 0
index: 0
index: 3
index: 3
index: 5
index: 5

【问题讨论】:

  • 您是否总是试图将所有字符加上它们的索引位置作为最终结果?或者得到更一般的东西(即告诉你第 5 个'z'在字符串中的位置的方法,或者如果传递一个字符串和一个字符,给你该字符的所有索引位置的方法)?展示一个返回你想要的东西的想象函数可能是值得的。 . .

标签: ruby string character


【解决方案1】:

使用Enumerator#with_index:

str = "sssaadd"
str.each_char.with_index do |char, index|
  puts "#{index}: #{char}"
end

【讨论】:

    【解决方案2】:

    如果你想找到所有重复子串的索引,你可以使用这个:

    'sssaadd'.enum_for(:scan, /(.)\1/).map do |match| 
      [Regexp.last_match.begin(0), match.first]  
    end
    # => [[0, "s"], [3, "a"], [5, "d"]]
    

    这里我们scan 使用正则表达式的所有字符串,它可以找到重复的字符。诀窍是 scan 的块形式不返回任何结果,因此为了使其返回块结果,我们将 scan 转换为枚举器并在其后添加 map 以获得所需的结果。

    另请参阅:ruby regex: match and get position(s) of

    【讨论】:

      【解决方案3】:

      你也用这个

        str = "sssaadd"
      
        arr=str.split('')
      
        arr.each_with_index do|char,index|
           puts "index : #{index}"
        end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-21
        • 1970-01-01
        • 2011-04-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多