函数指针写100个字符串中$的个数
时间: 2024-05-12 16:16:09 浏览: 14
好的,我会尽力回答你的问题。对于你的问题,我可以给你一个函数指针的示例代码:
```c
#include<stdio.h>
#include<string.h>
#define MAX_LENGTH 100
int count_char(char *str, char ch)
{
int count = 0;
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] == ch) {
count++;
}
}
return count;
}
void count_dollars(char **arr, int len, int (*fun_ptr)(char*, char))
{
for (int i = 0; i < len; i++) {
int count = (*fun_ptr)(arr[i], '$');
printf("The number of '$' in string %d is: %d\n", i+1, count);
}
}
int main()
{
char *str_arr[MAX_LENGTH] = {"$foo$barz$", "$baz$$quux$$$$$$", "$$$", "$$$quuxfoo$$$"};
count_dollars(str_arr, 4, &count_char);
return 0;
}
```
这个程序定义了一个`count_char`函数,用于计算字符串中某个字符出现的次数。然后定义了一个`count_dollars`函数,用于统计字符串数组中每个字符串中"$"的个数,具体实现是通过函数指针`fun_ptr`来调用`count_char`函数。在`main`函数中,定义了一个字符串数组`str_arr`,并调用`count_dollars`函数来统计"$"的个数。
如果您有更多问题,欢迎问我。