题目
输入三个字符串,第一个是原串,第二个是子串,第三个是替换串,将原串中的子串替换为替换串(不使用string类相关函数))
#include <iostream>
#include <cstring>
using namespace std;
void printStr(char temp[]){
cout<<"the string is:"<<temp<<endl;
}
//子串对比是否相等
inline int isequal(char* s1,char* s2 , int shead){
int s2len = strlen(s2);
for(int i=0;i<s2len;i++){
if(s1[shead+i]!=s2[i]){
return 0;
}
}
return 1;
}
void Replace(char* str,char* findStr,const char* replaceStr){
int strl = strlen(str); //原串长度
int findlen = strlen(findStr); //子串长度
int replen = strlen(replaceStr); //替换串长度
char temps[200];
int phead=0,j=0; //j用以控制temps数组的指针
for(int i=0;i<strl;i++){
if(!isequal(str,findStr,i)){
//如果从phead开始往后的子串和findstr不匹配,就把phead字符存入temps,phead后移,j后移
temps[j] = str[phead];
phead++;
j++;
}
else{
//若匹配,则将该子串存入temps,phead后移findlen(子串长度)
for(int k=0;k<replen;k++){
temps[j] = replaceStr[k];
j++;
}
phead += findlen;
}
}
printStr(temps);
}
int main()
{
char str[100],finds[20],replaces[20];
cout<<"please input string:";
cin.getline(str,100);
cout<<"please input son string:";
cin.getline(finds,20);
cout<<"please input replace string:";
cin.getline(replaces,20);
Replace(str,finds,replaces);
//printStr(str);
return 0;
}