我怎么算元音?

时间:2014-11-08 01:33:42

标签: ruby string

我已经看到了解决方案,它或多或少匹配

Write a method that takes a string and returns the number of vowels
 in the string. You may assume that all the letters are lower cased. You can treat "y" as a consonant.
Difficulty: easy.

def count_vowels(string)
    vowel = 0
    i = 0
    while i < string.length  
        if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
            vowel +=1
end

    i +=1

return vowel

end

puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}")
puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}")
puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}")
puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}")

5 个答案:

答案 0 :(得分:10)

def count_vowels(str)
  str.scan(/[aeoui]/).count
end

/[aeoui]/是一个正则表达式,基本上意味着“任何这些字符:a,e,o,u,i”。 String#scan方法返回字符串中正则表达式的所有匹配项。

答案 1 :(得分:4)

def count_vowels(str)
  str.count("aeoui")
end

答案 2 :(得分:0)

您的功能很好,您只是错过关键字end来关闭您的while循环

def count_vowels(string)
  vowel = 0
  i = 0

  while i < string.length
    if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
      vowel +=1
    end
  i +=1
  end
  return vowel
end

puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}")
puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}")
puts("count_vowels(\"colour\") == 3: #{count_vowels("colour") == 3}")
puts("count_vowels(\"cecilia\") == 4: #{count_vowels("cecilia") == 4}")


#=> count_vowels("abcd") == 1: true
#=> count_vowels("color") == 2: true
#=> count_vowels("colour") == 3: true
#=> count_vowels("cecilia") == 4: true

答案 3 :(得分:0)

我认为使用HashTable数据结构是解决这个特定问题的好方法。特别是如果你需要分别输出每个元音的数量。

以下是我使用的代码:

def vowels(string)

  found_vowels = Hash.new(0)

  string.split("").each do |char|
    case char.downcase
    when 'a'
      found_vowels['a']+=1
    when 'e'
      found_vowels['e']+=1
    when 'i'
      found_vowels['i']+=1
    when 'o'
      found_vowels['o']+=1
    when 'u'
      found_vowels['u']+=1
    end
  end

  found_vowels
end

p vowels("aeiou")

甚至这个(优雅但不一定表现):

def elegant_vowels(string)

  found_vowels = Hash.new(0)

  string.split("").each do |char|
    case char.downcase
    when ->(n) { ['a','e','i','o','u'].include?(n) }
      found_vowels[char]+=1
    end
  end

  found_vowels
end

p elegant_vowels("aeiou")

将输出:

  

{“a”=&gt; 1,“e”=&gt; 1,“i”=&gt; 1,“o”=&gt; 1,“u”=&gt; 1}

答案 4 :(得分:0)

因此,您不必将字符串转换为数组并担心区分大小写:

def getVowelCount(string)
  string.downcase.count 'aeiou'
end