c语言 - 我不知道如何在读取数组元素时遍历它们



我正在尝试编写一个程序来查找给定字符串中的所有元音,但是我不知道如何让我的程序增加我的计数变量(元音(

我一直在寻找"获取用于迭代的数组大小"等。无法找到特定于 C 的任何内容。

int num_vowels(char string[]){
//int j;
int i;
int numVowels = 0;
//iterate through string searching for vowels
for(i = 0; i < sizeof(string); i++){
//if any vowels found
if (string[i] == 'a' ||string[i] == 'e' ||string[i] == 'i' ||string[i] 
== 'o' ||string[i] == 'u'){
//increase count
numVowels++;
}
}
//print count
printf("Number of vowels: %d", numVowels);
return 0;
}

输入工作正常,只是我无法让它打印数字元音,甚至无法确定它是否正在通过数组。

编辑:我知道,这是一个很长的if语句,我稍后会修复它

当你写"num_vowels(char string[]("时,你传递的不是字符串,而是字符数组"string"的第一个元素的地址(指针(。

因此,当您执行"sizeof(string("时,结果将是字符指针的大小,根据体系结构的不同,可以是 4 或 8。

正如评论中所建议的,您可以使用"strlen",但请确保包含"string.h"标题.....解决方案将是.....

#include <stdio.h>
#include <string.h>
int num_vowels(char string[]){
int i;
int numVowels = 0;
//iterate through string searching for vowels
for(i = 0; i < strlen(string); i++){ //use strlen(string)
//if any vowels found
if (string[i] == 'a' ||string[i] == 'e' ||string[i] == 'i' ||string[i] 
== 'o' ||string[i] == 'u'){
//increase count
numVowels++;
}
}
//print count
printf("Number of vowels: %d", numVowels);
return 0;
} 

或者你不需要使用"strlen"并直接取消引用指针。 这样。。。。。。

int num_vowels(char string[]){
int i;
int numVowels = 0;
//iterate through string searching for vowels
for(; i = *string; string++){ //deference and increment pointer
//if any vowels found
if (i == 'a' || i == 'e' || i == 'i' || i 
== 'o' || i == 'u'){
//increase count
numVowels++;
}
}
//print count
printf("Number of vowels: %d", numVowels);
return 0;
}

对减少有条件if几乎没有帮助

#include <stdio.h>
#include <string.h>
int num_vowels(const char *string){
int numVowels = 0;
const char *wordToSearch = "aeiou";
//loop on string
for(int i = 0; i < strlen(string); i++) {
//loop on wordToSearch
for (int j = 0; j < strlen(wordToSearch); j++) {
if (string[i] == wordToSearch[j]) {
numVowels++;
}
}
}
printf("Number of vowels: %d", numVowels);
return 0;
}

最新更新