我如何计算元音? [英] How do I count vowels?
本文介绍了我如何计算元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经看到了解决方案,它或多或少是匹配的
I've seen the solution and it more or less matches
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}")
推荐答案
def count_vowels(str)
str.scan(/[aeoui]/).count
end
/[aeoui]/
是一个正则表达式,基本上表示这些字符中的任何一个:a、e、o、u、i".String#scan
方法返回字符串中正则表达式的所有匹配项.
/[aeoui]/
is a regular expression that basically means "Any of these characters: a, e, o, u, i". The String#scan
method returns all matches of a regular expression in the string.
这篇关于我如何计算元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文