编写一个函数 void DeleteCharOfStr(char *s, char ch) 函数的功能是删除字符串s中出现的所有指定的字符ch

2024-11-18 13:44:20
推荐回答(2个)
回答(1):

#include
void DeleteCharOfStr(char *s, char ch)
{
int i,j;
for(i=0;s[i];i++)
while(s[i]==ch)
for(j=i;s[j];j++)
s[j]=s[j+1];

}
int main(void)
{
char s[100],ch;
printf("输入一个字符串:\n");
gets(s);
printf("输入一个的字符:");
scanf("%c",&ch);
DeleteCharOfStr(s,ch);
printf("%s\n",s);
return 0;
}

回答(2):

char* DeleteCharOfStr(char *s, char ch)
{
int len = 0;
int i = 0;
int j = 0;
char *p = s;

len = strlen(p);
char *new_str = malloc(len+1);

for (i; i < len+1; i++)
{
if (p[i] != ch)
{
new_str[j] = p[i];
j++;
}
}
new_str[j] = 0;
return new_str;
}