如何在两个随机字符串中找到相同的字符?(Ruby)



我正忙着解决我在网上发现的一些问题,我觉得这应该很简单,但我真的很挣扎。

假设你有字符串'AbcDeFg'和下一个字符串'HijKgLMnn',我希望能够在字符串中找到相同的字符,所以在这种情况下,它将是'g'。

也许我没有提供足够的信息-我正在做代码降临,我是在第三天。我只需要第一个位的帮助,这是给你一串字符-你必须把字符分成两半,然后比较两个字符串。你基本上必须得到两者之间的共同特征。这是我目前拥有的:

file_data = File.read('Day_3_task1.txt')
arr = file_data.split("n")
finals = []
arr.each do |x|
len = x.length
divided_by_two = len / 2
second = x.slice!(divided_by_two..len).split('')
first = x.split('')
count = 0
(0..len).each do |z|
first.each do |y|
if y == second[count]
finals.push(y)
end
end
count += 1
end 
end
finals = finals.uniq

希望这对你的理解有帮助:)

您是否尝试使用String#char方法将两个字符串转换为数组并找到这些数组的交集?这样的:

string_one = 'AbcDeFg'.chars
string_two = 'HijKgLMnn'.chars
string_one & string_two # => ["g"]

一种方法是使用String#scan方法和正则表达式

rgx = /(.)(?!.*1.*_)(?=.*_.*1)/

我不提倡这种方法。我只是想一些读者可能会觉得有趣。

假设

str1 = 'AbcDgeFg'
str2 = 'HijKgLMnbn'

现在形成字符串

str = "#{str1}_#{str2}"
#=> "AbcDeFg_HijKgLMnbn"

我假设字符串只包含字母,在这种情况下,它们在str中用除字母以外的任何字符分隔。我用了下划线。当然,如果字符串可以包含下划线,则必须使用不同的分隔符。

然后计算

str.scan(rgx).flatten
#=> ["b", "g"]

array# flatten是必需的,因为

str.scan(rgx)
#=>[["b"], ["g"]]

正则表达式可以写成自由空格模式以使其自文档化:

rgx =
/
(.)    # match any character, same to capture group 1
(?!    # begin a negative lookahead
.*   # match zero or more characters 
1   # match the contents of capture group 1
.*   # match zero or more characters 
_    # match an underscore
)      # end the negative lookahead
(?=    # begin a positive lookahead
.*   # match zero or more characters 
_    # match an underscore
.*   # match zero or more characters 
1   # match the contents of capture group 1
)      # end the positive lookahead
/x     # invoke free-spacing regex definition mode

请注意,如果一个字符在str1中出现不止一次,在str2中至少出现一次,则负向前看确保只匹配str1中的最后一个字符,以避免返回重复项。


也可以写成

str.gsub(rgx).to_a

使用String#gsub的(第四种)形式,它接受单个实参,不带块,返回一个枚举数。

最新更新