我想创建一个函数来计算字符串str中字符c的出现次数,无论字符串c中的字符c是否为小写。我正在尝试使用toupper和tolower函数,但是它不起作用。
在主函数中,我想使用malloc函数为最多50个字符的字符数组动态分配内存,然后使用fgets读取输入字符串。然后,我想通过使用malloc函数但根据输入字符串的长度为输入字符串正确分配内存。然后,我想将输入字符串复制到正确大小的另一个字符串中,并释放开头分配的内存。我不知道为什么,但是malloc函数没有在一开始分配50个字符。当我打印输入字符串的长度时,它不算超过7个字符。我想念什么?
这是我的代码如下:
int count_insensitive(char *str, char c){
int count = 0;
for(int i = 0; str[i] != '\n'; i++){
if(( str[i] == toupper(c)) || str[i] == tolower(c) ){
count++;
}
}
return count;
}
int main(){
char *a_str;
a_str = (char *) malloc(sizeof(char) * 50);
fgets(a_str, sizeof(a_str), stdin);
printf("%lu\n", strlen(a_str));
char *a_str2;
a_str2 = (char *) malloc(sizeof(char) * (strlen(a_str)));
strcpy(a_str2, a_str);
printf("%s\n", a_str2);
free(a_str);
printf("The character 'b' occurs %d times\n", count_insensitive(a_str2, 'b'));
printf("The character 'H' occurs %d times\n", count_insensitive(a_str2, 'H'));
printf("The character '8' occurs %d times\n", count_insensitive(a_str2, '8'));
printf("The character 'u' occurs %d times\n", count_insensitive(a_str2, 'u'));
printf("The character '$' occurs %d times\n", count_insensitive(a_str2, '$'));
如果输入此字符串:
Hello world hello world
输出是这个:
7
hello w
The character 'b' occurs 15 times
The character 'H' occurs 47 times
The character '8' occurs 18 times
The character 'u' occurs 17 times
The character '$' occurs 6 times
通过执行chux注释和一些小的更改,这是代码的有效版本。我将在接下来的几个小时内写一些解释。
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int count_insensitive(char *str, char c){
int count = 0;
for(int i = 0; str[i] != '\n'; i++){
if(( str[i] == toupper(c)) || str[i] == tolower(c) ){
count++;
}
}
return count;
}
int main()
{
char *a_str;
a_str = malloc(50);
fgets(a_str, 50, stdin);
printf("%zu\n", strlen(a_str));
char *a_str2;
a_str2 = malloc(strlen(a_str));
strcpy(a_str2, a_str);
printf("%s\n", a_str2);
free(a_str);
printf("The character 'b' occurs %d times\n", count_insensitive(a_str2, 'b'));
printf("The character 'H' occurs %d times\n", count_insensitive(a_str2, 'H'));
printf("The character '8' occurs %d times\n", count_insensitive(a_str2, '8'));
printf("The character 'u' occurs %d times\n", count_insensitive(a_str2, 'u'));
printf("The character '$' occurs %d times\n", count_insensitive(a_str2, '$'));
}