您的位置:首页 > 文旅 > 旅游 > C++编程逻辑讲解step by step:字符串的查找和替换

C++编程逻辑讲解step by step:字符串的查找和替换

2025/2/24 14:34:24 来源:https://blog.csdn.net/workflower/article/details/140141504  浏览:    关键词:C++编程逻辑讲解step by step:字符串的查找和替换

题目

word中有查找和替换功能,编程实现在一个字符串中进行查找和替换的功能。


分析

题目不允许使用另外数组,要求在原数组上进行替换;需要不断地移动字符串,或者增长或者缩短,初始数组必须足够大。


代码

 

#include <iostream>
#include <cstring>
using namespace std;
char str[]="East China Normal University is very beautiful. I like East China Normal University very much. There is a big playground in East China Normal University. The teachers in East China Normal University are very kind. The students are very polite and smart.";
void search(char *, char*, int, int);
void replace(char *, char*, int, int);
int main(){char s1[50];           //s1 存放查找字符串 cout<<"Please enter the string you want to find: ";gets(s1);int l1=strlen(s1);    char s2[50];             //s2 存放替换字符串cout<<"Please enter the string to replace: ";gets(s2);int l2=strlen(s2);search(s1, s2, l1, l2);cout<<"The replaced array is :"<<endl;cout<<str<<endl;return 0;
} 
void replace(char *s2, char *p1, int l1, int l2){       //s2 接收替换字符串,p1 接收要替换位置的首字符地址,l1 存放查找字符串的长度,l2 存放替换字符串的长度 int i, j, k, m=l1-l2;char *r1, *r2;if(m>0){                                            //查找字符串大于替换,进行前移 for(i=0; i<l2; i++)                             //把原字符串替换 *(p1+i)=*(s2+i);for(j=l2; *(p1+m+j)!='\0'; j++)                 //前移操作 *(p1+j)=*(p1+m+j);*(p1+j)='\0';}else if(m<0){                                       //替换字符串大于查找,进行后移 i=strlen(str)-1;for(k=0; k<-m; k++)                             //铺路,把字符串结束标志向后移 m 个位置 *(str+i+k+1)=' ';            *(str+i+k+1)='\0';                              //路的末尾加上字符串结束标志 for( ; (str+i)>=(p1+l1); i--)                   //后移操作 *(str+i-m)=*(str+i);for(j=0; j<l2; j++)                             //把原字符串替换 *(p1+j)=*(s2+j);}else                                                //替换字符串等于查找for(r1=s2; r1<(s2+l1); r1++, p1++)*p1=*r1;	
}
void search(char *s1, char *s2, int l1, int l2){        //s1 接收查找字符串,s2 接收替换字符串,l1 存放查找字符串的长度,l2 存放替换字符串的长度char *p1, *p2, *s3;int i=1, j=0;bool flag=false;for(p1=str; *(p1+l1-1)!='\0'; p1++){if(*p1==*s1){if(*(p1+l1-1)==*(s1+l1-1)){                 //头尾字符相同,且长度相同 i=1;for(p2=p1, s3=s1; i<=l1; p2++, s3++, i++){if(*p2==*s3&&i==l1) flag=true;      //完全相同 if(*p2!=*s3) break;                 //发现不同,退出循环,较少情况 if(flag){replace(s2, p1, l1, l2);        //进行替换 j++;flag=false;}}	}}}if(j==0)cout<<"Not found!";                         //没找到 else cout<<"Found "<<j<<" results in all.";cout<<endl;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com