C++删除字符串中的子串

题目:

string str = "62354iijnjnij26758667ijn615468565ij"

将子字符串"ijn"全部删除

方法1:
该方法有个缺陷,它会将字符串中只要是ijn顺序的字符都会删除

    int pos = 0;
    while ((pos = str.find("ijn")) != -1)
    {
        str.erase(pos, 3);
    }
    cout << str << endl;

方法2:

    int i = 0;
    while (i < str.size()-2)
    {
        if (str[i] == 'i')
        {
            if (str.substr(i,3)=="ijn")
            {
                str.erase(i,3);
            }
            //if (str[i + 1] == 'j' && str[i + 2] == 'n')
            //{
            //  str.erase(i,3);
            //}
        }
        ++i;
    }
    cout << str << endl;

方法3:

    string::iterator it = str.begin();
    while (it != str.end() - 2)
    {
        if (*it == 'i')
        {
            if (*(it + 1) == 'j' && *(it + 2) == 'n')
            {
                str.erase(it - str.begin(),3);
            }
            //if (str.substr(it - str.begin(), 3) == "ijn")
            //{
            //  str.erase(it - str.begin(), 3);
            //}
        }
        ++it;
    }
    cout << str << endl;

你可能感兴趣的:(C++)