我正在尝试构建一种从字符串中删除元音的算法。下面的代码是我到目前为止所拥有的。
def shortcut(s)
s = s.split("")
for i in 0..s.length - 1 do
if ["a","e","i","o","u"].include?(s[i])
s.delete_at(i)
end
end
s.join
end
puts shortcut("hello world, we are the champions")
# => hll wrld, w r th chmpons
为什么 'o'
没有从字符串中删除?
最佳答案
通过删除一个字符,索引变得无效。
hello
^ before delete
01234
v after delete
hllo
您可以从头到尾迭代以解决它。
def shortcut(s)
s = s.split("")
(s.length - 1).downto(0) do |i|
if ["a","e","i","o","u"].include?(s[i])
s.delete_at(i)
end
end
s.join
end
但更好的解决方案是使用字符串替换方法,如 String#delete
, String#gsub
.
"hello world, we are the champions".gsub(/[aeiou]/, '')
=> "hll wrld, w r th chmpns"
关于ruby - 算法删除元音,意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36124623/