题目:
删除字符串中的子串
输入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 补码为:2的64次方-1
//s.size() - len_sub 后面出来一个很大很大的整数...
//解决方法是 (int)s.size() - len_sub