我们把字符串的数量、特定的字符和字符串放到一个文件strs.txt中,从文件中读入每个字符串。 编写一个函数count_specific_char,接受一个字符串、字符串的长度和一个字符作为输入,返回字符串中特定字符的数量。同一个字母的大写和小写都视为同一字符,可以使用ctype.h库中的tolower函数将每个大写字母转化为小写字母。 调用函数,最后将特定字符最多的字符串和特定字符在这个字符串中出现的次数写入到另一个文件spec.txt中。
时间: 2023-06-14 07:07:29 浏览: 57
下面是一个实现上述功能的示例代码:
```C
#include <stdio.h>
#include <ctype.h>
#define MAXLEN 100
int count_specific_char(char *str, int len, char c) {
int count = 0;
char lc = tolower(c);
for (int i = 0; i < len; i++) {
if (tolower(str[i]) == lc) {
count++;
}
}
return count;
}
int main(void) {
FILE *fp_str = fopen("strs.txt", "r");
FILE *fp_spec = fopen("spec.txt", "w");
char str[MAXLEN];
char spec_char;
int max_count = 0, count;
while (fgets(str, MAXLEN, fp_str) != NULL) {
int len = strlen(str);
if (len > 0 && str[len-1] == '\n') {
str[len-1] = '\0';
len--;
}
printf("Processing string: %s\n", str);
printf("Enter a specific character: ");
spec_char = getchar();
getchar(); // consume the newline character
count = count_specific_char(str, len, spec_char);
printf("Number of %c's in the string: %d\n", spec_char, count);
if (count > max_count) {
max_count = count;
fprintf(fp_spec, "%s %d\n", str, count);
}
}
fclose(fp_str);
fclose(fp_spec);
return 0;
}
```
在上述代码中,我们使用了标准库函数`fgets`从文件中逐行读入字符串,然后逐个处理每个字符串。在处理每个字符串时,我们使用了`count_specific_char`函数计算特定字符的数量。在计算完特定字符数量后,我们将最大数量的字符串以及特定字符数量写入到`spec.txt`文件中。
需要注意的是,由于`fgets`函数会将读入的行末的换行符也包含在字符串中,因此我们需要检查字符串的最后一个字符是否为换行符,如果是的话需要将其改为字符串结束符`\0`。此外,我们在读入特定字符后需要使用`getchar`函数消耗掉输入缓冲区中的换行符。