字符串去重——迭代器和erase的使用

来源:互联网 发布:access如何查询数据 编辑:程序博客网 时间:2024/06/05 14:47

string的erase方法可以回收内存,与vector不同。

1、问题描述:输入两个字符串,将第一个字符串中与第二个字符串相同的部分消掉,直到第一个字符串中没有与第二个字符串相同的部分。优先消除靠近第一个字符串串首的相同部分。假设两个字符串不会完全相同。

输入:两个字符串,以空格隔开,最大长度为256字符
输出:余下未消除的字符串
样例输入:abc121233 123 

样例输出:abc

#include <iostream>#include <string>using namespace std;int main(){string str1, str2, str3;cin >> str1 >> str2;for (string::iterator i = str2.begin(); i != str2.end();i++){for (string::iterator j = str1.begin();j!=str1.end();){if (*i == *j)j = str1.erase(j);elsej++;}}cout << str1 << endl;return 0;}
2、问题描述:消除字符串中相同的字符。

样例输入:aabcdefff

样例输出:abcdef

#include <iostream>#include <string>using namespace std;int main(){        string str1;cin >> str1;for (string::iterator i = str1.begin(); i < str1.end() - 1;i++)    //最后一个字符不用判断{for (string::iterator j = i + 1; j != str1.end();){if (*j == *i)j = str1.erase(j);elsej ++;}}cout << str1<< endl;return 0;}

思考:如果把第一个循环中的判断条件改成i!=str1.end()-1;会出现什么问题?

如果改成上述条件,那么当i指向倒数第二个字符,如果倒数第二个跟最后一个字符相同,最后一个字符被消除,那么此时i指向的倒数第二个字字符就变成了最后一个字符,i=str1.end()-1,然后执行i++,这样判断条件就失效了,会出现未知的错误。

如果非要用i!=str1.end()-1来判断的话,那么就需要在执行i++之前进行一下判断,把判断语句写到代码块中,if(i!=str1.end()-1)  i++;else break;

0 0
原创粉丝点击