我的代码找到元音的数量不起作用[关闭]

问题描述 投票:-3回答:3
def count_vowels(string)
  count_vowels = 0
  my_vowels = ["a" "e" "i" "o" "u"]
  idx = 0
  while idx < string.length
    gdx = 0
    while gdx < my_vowels.length
      if string[idx] == my_vowels[gdx]
        count_vowels = count_vowels + 1
      else
        gdx = gdx + 1
      end
    end
    idx = idx + 1
  end

  return count_vowels
end
ruby
3个回答
0
投票
while gdx < my_vowels.length
      if string[idx] == my_vowels[gdx]
        count_vowels = count_vowels + 1
      else
        gdx = gdx + 1
      end
end

应该:

while gdx < my_vowels.length
          if string[idx] == my_vowels[gdx]
            count_vowels = count_vowels + 1
            gdx = gdx + 1
          else
            gdx = gdx + 1
          end
end

因为你在找到元音后没有推进你的gdx计数器。所以它在找到第一个元音后最终会循环。

同样修复数组声明,工作代码可能是这样的:

def count_vowels(string)
  count_vowels = 0
  my_vowels = ["a", "e", "i","o","u","y"]
  idx = 0
  while idx < string.length
    gdx = 0
    while gdx < my_vowels.length
      if string[idx] == my_vowels[gdx]
        count_vowels = count_vowels + 1
        gdx=gdx+1
      else
        gdx = gdx + 1
      end
    end
    idx = idx + 1
  end

1
投票
def count_vowels(str)
  str.downcase.count("aeiou")
end

count_vowels("All the king's horses and all the king's men...")
  #=> 10

0
投票

试试这种方法

def count_vowels(string)
  ['a', 'e', 'i', 'o', 'u'].inject(0) { |sum, el| sum += string.downcase.count(el) }
end

请注意我为输入字符串做了downcase以减少迭代量。如果你有另一个逻辑 - 只需删除它。

© www.soinside.com 2019 - 2024. All rights reserved.