【发布时间】:2020-01-29 06:29:12
【问题描述】:
我想创建一个函数来计算字符串 str 中字符 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
【问题讨论】:
-
Hannah McDermott,很好奇,为什么在
printf("%lu\n", strlen(a_str));中使用"%lu"而不是"%zu"?
标签: c string function dynamic allocation