题目:
string str = "62354iijnjnij26758667ijn615468565ij"
将子字符串"ijn"
全部删除
方法1:
该方法有个缺陷,它会将字符串中只要是ijn顺序的字符都会删除
int pos = 0;
while (string::npos != (pos = str.find("ijn")) )
{
str.erase(pos, 3);
}
cout << str << endl;
方法2:
int i = 0;
while (i < str.size()-2)
{
if ('i' == str[i])
{
if ("ijn" == str.substr(i,3))
{
str.erase(i,3);
continue;
}
//if ('j' == str[i + 1] && 'n' == str[i + 2] )
//{
// str.erase(i,3);
// continue;
//}
}
++i;
}
cout << str << endl;
方法3:
int pos = 0;
while (pos < str.size() - 2) {
if ("ijn" == str.substr(pos, 3)) {
str.erase(pos, 3);
}
else {
++pos;
}
}
cout << str << endl;
方法4:
string::iterator it = str.begin();
while (it != str.end() - 2)
{
if ('i' == *it)
{
if ('j' == *(it + 1) && 'n' == *(it + 2))
{
str.erase(it - str.begin(),3);
continue;
}
//if ("ijn" == str.substr(it - str.begin(), 3))
//{
// str.erase(it - str.begin(), 3);
// continue;
//}
}
++it;
}
cout << str << endl;