用函数指针写100个字符串中$的个数
时间: 2024-05-10 09:21:08 浏览: 76
很高兴为您解答。以下是使用函数指针写100个字符串中$的个数的示例代码:
```c
#include <stdio.h>
#include <string.h>
int count_char(char *str, char ch) {
int count = 0;
while (*str != '\0') {
if (*str == ch) {
count++;
}
str++;
}
return count;
}
int main() {
char strings[100][100] = {
"apple$pear",
"hello!world$",
"abcd$$efg",
"1234",
"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$",
"", // an empty string
"$", // a string with only one $
"shi$san$shi",
"2$2=4",
"#$%^&",
"[[[[[[[[[[[[[[[[[[["
// ... and so on for 90 more strings ...
};
int (*count_char_ptr)(char *, char) = &count_char;
char ch = '$';
int total_count = 0;
for (int i = 0; i < 100; i++) {
int count = count_char_ptr(strings[i], ch);
printf("Count of %c in string %d: %d\n", ch, i+1, count);
total_count += count;
}
printf("Total count of %c in all strings: %d\n", ch, total_count);
return 0;
}
```
该程序声明了一个二维字符数组`strings`,其中包含了100个字符串;以及一个指向函数`count_char`的函数指针`count_char_ptr`。在`main`函数中,通过循环遍历每个字符串,使用函数指针`count_char_ptr`计算每个字符串中字符`'$'`的个数,并输出结果。最后,程序计算所有字符串中字符`'$'`的总数,并输出结果。
如果您有任何问题,欢迎随时提出。
阅读全文