Swift中的元音计数 [英] Counting Vowels in Swift
本文介绍了Swift中的元音计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在Java和C ++中成功完成了此操作,但是在Swift中却无法解决.这是我的C ++代码:
I have done this successfully in Java and C++ but can't figure it out in Swift. Here is my C++ code:
int count_vowels (string input)
{
int position = 0;
for (int i = 0; i < input.length(); i++)
{
char ch;
ch = input[i];
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){
position++;
}
}
return position;
}
再次,我只是尝试遍历一个字符串,计算if语句中为true的值,然后返回位置(有多少个).
Again I'm just trying to iterate through a string, counting the values that are true in the if statement and returning the position(how many there are).
有什么方法可以将其转换为快速语法.
Is there any way to convert this to swift syntax.
我知道了:
用于元音字符中的字符{
for char in vowels.characters{
if char == ("a") || char == ("e") || char == ("i") || char == ("o") || char == ("u") {
count++
}
}
谢谢大家的帮助和贴子,我正为此努力.
Thanks everybody for there help and posts I was pulling my hair out on this one.
再次感谢
推荐答案
您可以执行以下操作:
extension String {
var numberOfVowels: Int {
let vowels = "aeiou"
let vowelsSet = NSCharacterSet(charactersInString: vowels)
let strippedComponents = lowercaseString.componentsSeparatedByCharactersInSet(vowelsSet)
let stripped = strippedComponents.joinWithSeparator("")
return characters.count - stripped.characters.count
}
}
"Hello".numberOfVowels
这篇关于Swift中的元音计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文