用c语音统计字符串中元音字母的个数
时间: 2023-08-24 19:08:23 浏览: 60
可以使用C语言编写一个函数来统计给定字符串中元音字母的数量。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int count_vowels(char *str) {
int count = 0;
for (int i = 0; i < strlen(str); i++) {
switch(str[i]) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
count++;
break;
default:
// Do nothing
break;
}
}
return count;
}
int main() {
char str[] = "Hello, world!";
int vowel_count = count_vowels(str);
printf("The number of vowels in the string is %d\n", vowel_count);
return 0;
}
```
在上面的代码中,`count_vowels`函数遍历给定字符串中的每个字符,并使用`switch`语句检查是否为元音字母。如果是,计数器`count`就会增加1。最后,函数返回计数器的值。在`main`函数中,我们将一个字符串传递给`count_vowels`函数,并将返回的元音字母数量打印到屏幕上。