查找字符串 Ruby 中的第一个重复字符

Sha*_*ikh 0 ruby

我正在尝试在 Ruby 中调用字符串中的第一个重复字符。我已经使用gets定义了一个输入字符串。

如何调用字符串中的第一个重复字符?

到目前为止,这是我的代码。

string = "#{gets}"
print string
Run Code Online (Sandbox Code Playgroud)

我如何从这个字符串中调用一个字符?

编辑1:

这是我现在拥有的代码,我的输出出现在我面前 没有重复 26 次。我认为我的 if 语句写错了。

string "abcade"
puts string
for i in ('a'..'z')
if string =~ /(.)\1/
puts string.chars.group_by{|c| c}.find{|el| el[1].size >1}[0]
else
puts "no duplicates"
end
end
Run Code Online (Sandbox Code Playgroud)

我的第二个 puts 语句有效,但使用 for 和 if 循环,无论字符串是什么,它都不会返回 26 次重复项。

dav*_*rac 5

以下返回第一个重复字符的索引

the_string =~ /(.)\1/
Run Code Online (Sandbox Code Playgroud)

例子:

'1234556' =~ /(.)\1/
=> 4
Run Code Online (Sandbox Code Playgroud)

要获取重复字符本身,请使用$1

$1
=> "5"
Run Code Online (Sandbox Code Playgroud)

if语句中的示例用法:

if my_string =~ /(.)\1/
  # found duplicate; potentially do something with $1
else
  # there is no match
end
Run Code Online (Sandbox Code Playgroud)


flo*_*oum 5

s.chars.map { |c| [c, s.count(c)] }.drop_while{|i| i[1] <= 1}.first[0]
Run Code Online (Sandbox Code Playgroud)

采用Cary Swoveland的精致形式:

s.each_char.find { |c| s.count(c) > 1 }
Run Code Online (Sandbox Code Playgroud)

  • 考虑简化: `s.each_char.find { |c| s.count(c) &gt; 1 }`。请注意,“s.each_char”是一个枚举器,它比(临时)数组“s.chars”更有效。无论如何,这是对我在回答中给出的问题的第二种解释的解决方案。+1。 (2认同)