我仍在学习 C,并且一直在尝试找出计算数组中字符出现次数的最佳方法。
我计划将其分成函数并对其进行大量扩展,但到目前为止,我想出的最好的工作代码是一个更大的版本:
#define SIZEONE 7
#define SIZETWO 3
int main(void)
{
int arrOne[SIZEONE] = {97, 97, 98, 99, 99, 99, 99};
char arrTwo[SIZETWO] = {'a', 'b', 'c'};
int arrThree[SIZETWO] = {0};
int countOne = 0;
int countTwo = 0;
int countThree = 0;
for(countOne = 0; countOne < SIZEONE; countOne++)
{
for(countTwo = 0; countTwo < SIZETWO; countTwo++)
{
if(arrOne[countOne] == arrTwo[countTwo])
{
arrThree[countTwo] = arrThree[countTwo] + 1;
}
}
}
for(countThree = 0; countThree < SIZETWO; countThree++)
{
printf("%c ",arrTwo[countThree]);
}
countThree = 0;
printf("\n");
for(countThree = 0; countThree < SIZETWO; countThree++)
{
printf("%d ",arrThree[countThree]);
}
return 0;
}
从中我应该得到类似的东西:
a b c
2 1 4
我只是想知道是否有一种更简单的方法可以做到这一点,在我开始使用此方法之前有人可以向我指出或给我一个例子。
最佳答案
您可以尝试插入此函数作为所有数组大小的示例:
int findOccurences(const char *array, const int array_size, const char ch_to_find)
{
int found = 0;
for(int i = 0; i < array_size; ++i)
{
if(array[i] == ch_to_find) found++;
}
return found;
}
最好用有意义的名称来命名变量。对于您和其他可以阅读您的代码的人来说,这将更容易阅读。
关于c - 有没有更好的方法来查找一个字符在 C 中的数组或字符串中出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19295969/