我需要创建一个接受字符串和字符的函数,该函数需要删除字符串中所有出现的字符并返回删除的字符总数。我已设法修改字符串以便能够删除不需要的字符,但我似乎无法用新字符串替换旧字符串。感谢您提前回复。
这是我到目前为止所做到的:
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;
}
最佳答案
您创建了一个新字符串,但尚未使用它。您可以使用 memcpy
或 strcpy
等函数来复制内容。您也不会释放 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/