字符串中的子串替换

用字符串s代替主串中指定的子字符串,两者长度不一定相等

#include <iostream>
#include <string>

using namespace std;
void StrReplace(char* strSrc, const char* strFind, const char*strReplace);//原串、原串中待替换的串,替换串 (替换串和待替换的串长度不一定相等)


int main()
{
    string strFind,strReplace;
    cout << "Input the start string :" << endl;
    char *s = new char[100];
    /*gets(s)(可直接调用,不用另外赋值给字符指针)是直接读取字符串到buffer中,不检查是否越界,gets_s有对长度的控制,超过会有提醒,fgets()从文件中读取*/
    gets_s(s,100);  
    cout << "Input the sub_string to be replaced :" << endl;
    getline(cin,strFind);
    const char *sub_str = strFind.c_str();
    cout << "Input the replacement:" << endl;
    getline(cin,strReplace);
    const char *replace = strReplace.c_str();
    StrReplace(s,sub_str,replace);
    cout << "The end string after the replacement:" << endl;
    cout << s << endl;
    return 0;
}

void StrReplace(char* strSrc, const char* strFind, const char*strReplace)
{
    int n = strlen(strFind);
    /*因为strFind 和strReplace长度不一定相等,所以不能直接在strSrc中处理,需要额外创建一个空间,存储替换后的字符串*/
    char *temp = new char[100];    
    char *q = temp;
    char *s = strSrc;
    const char *p = strReplace;
    while(*s != '\0')
    {
        if(strncmp(s,strFind,n) == 0)
        {
                while (*p != '\0')
                {
                    *q = *p;
                    q++;
                    p++;
                }
                p = strReplace;
                s += n;
        }
        else
        {
            *q = *s;
            s++;
            q++;
        }
    }
    *q = '\0';
    strcpy(strSrc,temp);
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值