c - 从字符串中删除不需要的字符的函数

标签 c string function replace

我需要创建一个接受字符串和字符的函数,该函数需要删除字符串中所有出现的字符并返回删除的字符总数。我已设法修改字符串以便能够删除不需要的字符,但我似乎无法用新字符串替换旧字符串。感谢您提前回复。

这是我到目前为止所做到的:

int clearstr(char *st,char u){
    int i,j=0,total=0,size=strlen(st);
    char *new_str=calloc(size,sizeof(char));
    for(i=0;i<size;i++){
        if(st[i]!=u){
            new_str[j]=st[i];
            j++;}
        else total++;
    }
    new_str[j]='\0';
    printf("%s",new_str);

    //until here all is good ,new_str has the modified array that i want but i can't find a way to replace the string in st with the new string in new_str and send it back to the calling function (main),thanks for any help // 

    return total;
}

最佳答案

您创建了一个新字符串,但尚未使用它。您可以使用 memcpystrcpy 等函数来复制内容。您也不会释放 calloc 调用的内存;这会造成内存泄漏。尝试这样的事情:

...
new_str[j]='\0';
printf("%s",new_str);

strcpy(st, new_str); // Copy the contents of the new string to the original one
free(new_str); // Clear the memory of the allocation in this function, otherwise you get a memory leak

return total; 
...

关于c - 从字符串中删除不需要的字符的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325666/

相关文章:

c - 如何在 windows VS2012 或 VS2010 上设置 GStreamer Editing Services 1.2.0 (GES) 环境

python - Python 3 中变量的简单表达式

r - 使用 'bquote'(或替代方法)从符号构造函数

c - 从二维数组中删除最大和最小数字而不进行排序

C - 将数组中的 char 字符串排序为等于 char 用户输入

java - 我有一个包含 3 列和 7 行的文件,我需要从文件中的每一列中创建 3 个数组

java - 添加 "\0"(null)后是否可以向字符串添加数据?

c# - 如何取消引用 LINQ 中可能为空的字符串

c - 如何将数字添加到字符串的每个字符

java - C 和 Java 在变量方面的区别?