题目 删除字符串中的子串 题解

题目:
删除字符串中的子串
输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2。

输入格式:
输入在2行中分别给出不超过80个字符长度的、以回车结束的2个非空字符串,对应S1和S2。

输出格式:
在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串。

输入样例:
Tomcat is a male ccatat
cat
输出样例:
Tom is a male

思路:
方法1:
From:http://blog.csdn.net/attack2001/article/details/46625123
用 char *strstr( const char *str1, const char *str2 )(#include

//删除字符串子串 
//方法一 

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
using namespace std;
const int maxn = 100;
char s[maxn],subs[maxn];

void sub_erase1(){
    while (strstr(s, subs) != NULL){
        char *c = strstr(s, subs);
        char tmp[maxn] = "\0";
        int len_s = strlen(s);
        int len_subs = strlen(subs);
        strcpy(tmp, c);
        int len_tmp = strlen(tmp);

        strcpy(s + len_s - len_tmp, tmp + len_subs);
    }
}


int main(int argc, char** argv) {

    gets(s);
    gets(subs);

    sub_erase1();   
    cout<<s<<endl;

    return 0;
}

Code2:

//方法二

#include <iostream>
#include <string> 
#include <fstream>

using namespace std;
string s,subs;
int len_sub;

void sub_erase2(){
    int i = 0;
    bool iserase;
    while (i <= ((int)s.size() - len_sub)) {

        iserase = false;            //重置. 
        if(s[i] == subs[0]){
            if(s.substr(i, len_sub) == subs){
                s.erase(i, len_sub);

                //向前回退  因为有s = ppatat,sub = pat,这种情况 
                if(i - (len_sub - 1) < 0){
                    i = 0;
                }
                else{
                    i -= (len_sub - 1);
                }
                iserase = true;
            }
        }
        if(!iserase) ++i;
    }
}

int main(){
//  fstream cin("a.txt");

    getline(cin, s);
    getline(cin, subs);
    len_sub = subs.size();

    sub_erase2();
    cout<<s<<endl;

    return 0;
}

Code2遇到的错误…( Ĭ ^ Ĭ )….

//错因
//iserase 忘记重置还原了...
//out_of_range :越界访问:
//越界的原因:s.size() 是unsigned long类型,而len_sub是int类型,两个类型相减,
//len_sub转成unsigned long类型,-1在内存中 绝对值取反加1  补码为:264次方-1 
//s.size() - len_sub 后面出来一个很大很大的整数...
//解决方法是 (int)s.size() - len_sub
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值