c - 为任意长度的字符串动态分配内存

标签 c string function dynamic allocation

我想创建一个函数,计算字符串 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

最佳答案

通过执行 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, '$'));

}

关于c - 为任意长度的字符串动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58159793/

相关文章:

c - 在内联汇编中读取非标准大小的寄存器(ID​​TR)(容易吗?)

c - 矩阵元素的乘法

c - 如何从 Clang 中的 Expr 对象获取 Stmt 类对象

c - 重新排列字符串字母

r - 从字符串中选择第n个字符

c++ - 如何在 C++ 中计算相邻的元音?

javascript - 如何在javascript中获取输入并调用函数

javascript - 仅允许 Javascript 函数在前一个函数完成后运行

python - 在函数中将类的属性名称作为参数传递

swift - 基于多个字符串定界符拆分字符串的高效算法