输入三个字符串,第一个是原串,第二个是子串,第三个是替换串,将原串中的子串替换为替换串(不使用string类相关函数))

题目

输入三个字符串,第一个是原串,第二个是子串,第三个是替换串,将原串中的子串替换为替换串(不使用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;
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值