简体   繁体   English

获取ruby中所有字符的索引

[英]Get the index of all characters in ruby

I am trying to get the index of string which has duplicate characters. 我试图获取具有重复字符的字符串的索引。 But if I have same characters it keeps returning the index of first occurrence of that character 但是如果我有相同的字符,它会一直返回该字符第一次出现的索引

    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

Use Enumerator#with_index : 使用Enumerator#with_index

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

If you want to find all indices of duplicated substrings, you can use this: 如果要查找重复子字符串的所有索引,可以使用以下命令:

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

Here we scan all the string by regex, that finds duplicated characters. 在这里,我们通过正则表达式scan所有字符串,找到重复的字符。 The trick is that block form of scan doesn't return any result, so in order to make it return block result we convert scan to enumerator and add a map after that to get required results. 诀窍是块形式的scan不会返回任何结果,因此为了使其返回块结果,我们将scan转换为枚举器并在此之后添加一个map以获得所需的结果。

See also: ruby regex: match and get position(s) of 另请参阅: ruby regex:匹配并获取位置

You also use this 你也用这个

  str = "sssaadd"

  arr=str.split('')

  arr.each_with_index do|char,index|
     puts "index : #{index}"
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM