计算字符串中的元音数

Counting the number of vowels in a string

本文关键字:字符串 计算      更新时间:2023-10-16

我正在编写一个返回给定字符串的元音数的函数,这是代码:

int isVowel(string sequence)
{   
    int numberOfVowels = 0;         //Initialize number of vowels to zero
    string vowels = "aeiouAEIOU";   //Possible vowels, including capitals
    for (int i = 0; i <= sequence.length(); i++)
    {
        for (int j = 0; j <= vowels.length(); j++)
        {
            if (sequence[i] == vowels[j])
            {
                numberOfVowels += 1;
            }
        }
    }
    return numberOfVowels;
}

这将返回答案。例如," a"的输入返回2," aa"的输入返回3,等等

i <= sequence.length()

<=几乎在循环中永远都不正确,因为C 使用了0基于0的索引。相反,您应该做

i < sequence.length()