题目 删除字符串中的子串 题解
2018-03-19 23:00
302 查看
题目:
删除字符串中的子串
输入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
Code2:
Code2遇到的错误…( Ĭ ^ Ĭ )….
删除字符串中的子串
输入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
相关文章推荐
- PTA基础题目5-29删除字符串中的子串
- 7-29 删除字符串中的子串
- 字符串-02. 删除字符串中的子串(20)
- 删除字符串中的指定子串
- 5-29 删除字符串中的子串*
- 删除字符串中的子串
- 10-2. 删除字符串中的子串(20)
- 删除字符串中的子串(返回子串)
- 删除字符串中所有给定的子串
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- 字符串-02. 删除字符串中的子串(20)
- 【C++】删除字符串中的子串
- 指针解决字符串删除子串
- 10-2. 删除字符串中的子串(20)
- 10-2. 删除字符串中的子串(20)
- 阿里实习生电面题目:输出给定字符串的全部连续子串 这是我的感悟
- 题目1168:字符串的查找删除(字符串操作)
- C++删除字符串中的子串
- 删除字符串中的子串
- 用JAVA正则表达式 删除字符串的特定子串