C语言小程序——字符串的比对与替换

来源:互联网 发布:淘宝充值方式 编辑:程序博客网 时间:2024/05/18 00:33
#include<stdio.h>   //输入三个字符串,若s中含有t1,则用t2覆盖s中的t1,反之原样输出s;若t1与t2不等长则报错;#include<string.h>void fun (char*s,char*t1,char*t2,char*w){char *p,*q;strcpy(w,s);while(*w){p=w;q=t1;while(*q){if(*p==*q){p++;q++;}else break;      /*此else语句相当重要,不可缺少。若缺少,程序无法正常执行*/}  if(*q=='\0')   //字符串匹配成功{p=w;q=t2;while(*q){*p=*q;p++;q++;}}w++;}}  int main(){  char  s[100],t1[100],t2[100],w[100];  printf("Please enter string s:"); scanf("%s", s);  printf("Please enter substring t1:"); scanf("%s", t1);  printf("Please enter substring t2:"); scanf("%s", t2);  if(strlen(t1)==strlen(t2))   {  fun( s, t1, t2, w);      printf("The result is:%s\n", w);  }  else    printf("Error:strlen(t1)!=strlen(t2)\n");  return 0 ;}

1 0