c语言编写一个程序,实现查找一个字符串中的特定字符,并将其删除.

如题所述

一、算法描述

逐个比较字符串source中的字符,若当前i位置的字符等于待删除字符ch,则i+1..len-1之间的子串整体前移;如此反复,直到所有待删除字符都找到并被删除为止。


二、操作过程


三、参考程序

#include <stdio.h>
#include <string.h>

/* ç§»é™¤å­—符串source中的所有ch字符 */
void remove(char *source, char ch);

void main()
{
char source[1000];
char ch;

printf("请输入一个字符串:");
gets(source);
printf("请输入待删除字符:");
ch = getchar();

remove(source, ch);

printf("新的字符串:");
puts(source);
}

/* ç§»é™¤å­—符串source中的所有ch字符 */
void remove(char *source, char ch)
{
int i, j;
int len = strlen(source);

for(i=0; source[i]!='\0'; i++)
{
if(source[i] == ch)
{
for(j=i+1; source[j]!='\0'; j++)
{
source[j-1] = source[j];
}
source[j-1] = '\0';
}
}
}


四、运行测试

请输入一个字符串:How are you?
请输入待删除字符:o
新的字符串:Hw are yu?
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-15

挑出其中需要的字符存回来就行了

#include "stdio.h"

#include "string.h"

#include "stdlib.h"

void delChar(char *str,char m)

{

    int len=strlen(str);

    int i,j=0;

    char *p=(char *)malloc(len*sizeof(char));

    memset(p,0,len);

    for(i=0;i<len;i++)

    {

          if(*(str+i)!=m)

            *(p+j++)=*(str+i);

    }

    memset(str,0,len);

    strncpy(str,p,strlen(p));

    free(p);

}

int main()

{

    char str[100]={0};

    char del;

    scanf("%s %c",str,&del);

    delChar(str,del);

    puts(str);

   

}

结果:

追问

好厉害啊!

追答

一般般,呵呵

追问

请编写函数countvalue(),它的功能是:求n以内(不包括n)同时能被3和7整数的所有自然数之和的平方根s,并作为函数值返回,最后结果s输出到文件out.dat中。
例如若n为1000时,函数值应为:s=153.909064。这个怎么做?

追答#include "stdio.h"
#include "math.h" 
double  countvalue(int n)
{
  int i,sum=0;
  for(i=1;i<n;i++)
   if(i%3==0 && i%7==0)
     sum+=i;
  return sqrt(sum*1.0);
}
int main()
{
  FILE *fp;
  double sum;
  int n;
  scanf("%d",&n);
  sum=countvalue(n);
  fp=fopen("out.dat","w");
  fprintf(fp,"%lf",sum);
  fclose(fp);
}

本回答被网友采纳
第2个回答  推荐于2018-03-18
char chr[5] = "abccd";
char chr1[1] = "c";
int j=0;
for(int i =0;i<5;i++)
{
if(chr[i]=="c")
j++;//先算出有几个符合的
}
char chrNew[j];
int m=0;
for(int k =0 ; k<5;k++)
{
if(chr[k]!="c")
chrNew[m] = chr[k];
m++;
}
此时获得的chrNew就是新的删除之后的字符串
基本类型中不支持删除操作,所以实际上就是一个新的字符串。本回答被网友采纳
第3个回答  推荐于2016-04-08
#include<stdio.h>
#include<string.h>
main()
{char a[80];
int i,j,pos,y;
char ch;
while(true)
{
printf("请输入一行字符串:\n");
gets(a);
printf("请输入要删去的字符:\n",ch);
scanf("%c",&ch);
for(i=0;i<strlen(a);i++)
if(a[i]==ch)
{ pos=i;
a[pos]=' ';
}
for(j=pos;j<strlen(a)-1;j++)
a[j]=a[j+1];
a[strlen(a)-1]='\0';
printf("%s\n",a);
printf("退出输入0,继续输入1:\n");
scanf("%d",&y);
if(y==1)
scanf("%c",&ch);
if(y==0)
break;
}本回答被提问者采纳
第4个回答  2013-04-15
这个比较简单,先strchr查找下,然后memmov就可以了
相似回答