我必须创建一个程序,它需要用户输入两个单词,并从两个单词中提取唯一的字母。
两个词是“外推法”和“之间”
在移除公共字母表之后,结果应该是“extrpolatimg”,而不管馈送的单词的顺序。因为虽然外推法中有两个a,但只有一个被删除。
代码由我写到现在作为下
puts "Enter the first_word : "
word_1 = gets.chomp.downcase.split('', 0)
puts "Enter second word name: "
word_2 = gets.chomp.downcase.split('', 0)
p word_1
p word_2
differences = word_1- word_2
p differences
#input1 = among
#input2 = extrapolation
# output => ["m","g"]
字符串
代码会忽略第二个单词中第一个单词中没有的字母。
是否有任何内置的字符串方法来处理这个问题?
提前感谢您的帮助。
4条答案
按热度按时间dba5bblo1#
您可以使用
sub
来替换模式的第一次出现:(可以是单个字符)字符串
你也可以通过传递一个空字符串作为替换来 * 删除 * 第一个出现的字符串:
型
这可以在循环中用于从一个字符串替换另一个字符串中的所有字符:
型
为了避免每次迭代都创建一个新字符串,您可以对字符串重复调用
sub!
,这将就地修改接收者。但是,由于这种修改,您必须对输入进行dup
,以避免修改input1
:型
这可以通过使用
with_object
进一步重构,这对于在方法内部提供隐式返回值特别有用:型
从性能方面来说,这种方法可能不适合(非常)大的字符串,因为它将对第二个字符串中的每个字符遍历第一个字符串一次(反之亦然)。
h9vpoimq2#
假设我们有两个词。
字符串
型
的字符串
型
型
型
这与所需的字符串
"extrpolatimg"
不同。原因是我删除了每个要删除的字母的第一个示例,而所需的字符串是通过删除每个字符串的第一个"a"
和每个字符串的最后一个"o"
获得的。要么是OP在给出期望的结果时犯了错误,要么是我不理解确定哪个字母的示例要被删除的规则。我没有提到大写字母可能出现的情况,因为我不知道适用于这种情况的规则。
5fjcxozz3#
对于手头的任务,你可以通过稍微改变你的方法来完成它。Ruby虽然很棒,但它允许我们使用chars方法将字符串转换为字符数组。所以,你可以用chars替换split('',0)。
这里的逻辑是首先创建第二个单词的字符的副本。然后,迭代第一个单词的字符。如果在第二个单词的副本中找到字符,则将其从第一个单词和第二个单词的副本中删除。这两个词中剩下的都是独特的字符。
让我们把它转换成代码:
字符串
在此代码中,我们使用delete_at方法删除数组中特定索引处的字符,并使用index方法查找字符第一次出现的索引。方法检查数组是否包含特定字符。
vohkndzv4#
我会这样做:
字符串