【问题标题】:Function that removes unwanted character from string从字符串中删除不需要的字符的函数
【发布时间】:2017-09-14 12:29:37
【问题描述】:

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

这是我到目前为止所管理的:

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;
}

【问题讨论】:

  • new_str[j]='\0'; for(i=0;i

标签: c string function replace


【解决方案1】:

您创建了一个新字符串,但尚未使用它。您可以使用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; 
...

【讨论】:

  • 非常感谢这就是我一直在寻找的东西,但我无法让它为我的生活服务:D
猜你喜欢
  • 2011-12-24
  • 2016-06-29
  • 2015-08-06
  • 2011-02-16
  • 1970-01-01
  • 2016-02-01
  • 2021-01-13
相关资源
最近更新 更多