dimanche 31 janvier 2016

How to set end condition of string iterator in C++?

i'm new in C++. I met a problem when doing exercise in C++ Primer 5th edition(Ex 9.43). The for loop can't stop in my function find_and_replace. Here is the code:

#include <iostream>
#include <string>

int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace);

int main(int argc, char const *argv[])
{

    std::string str("I am a very loooooong string to be process!");
    int find_times;
    find_times = find_and_replace(str, "a", "###");
    std::cout << find_times << std::endl;
    std::cout << str << std::endl;

    return 0;
}

int find_and_replace(std::string& org_str, const std::string& str4find, const std::string& str4replace)
{
    int find_times = 0;

    if (org_str.size() < str4find.size())
    {
        std::cout << "Error: The original string is too short!" << std::endl;
        return find_times;
    }
    else if (org_str == str4find)
    {
        org_str.assign(str4replace);
        ++find_times;
        return find_times;
    }

    for (auto i = org_str.begin(), j = i + str4find.size(); j != org_str.end(); )
    {
        std::string temp(i, j);
        // std::cout << temp << std::endl;
        if (temp == str4find)
        {
            j = org_str.erase(i, j);
            org_str.insert(i, str4replace.begin(), str4replace.end());
            // std::cout << org_str << std::endl;
            // std::cout << *i << std::endl;
            j = i + str4find.size();
            // std::cout << *j << std::endl;
            ++find_times;
        }
        else
        {
            ++i;
            ++j;
        }
    }

    if (org_str.substr(org_str.size() - str4find.size()) == str4find)
    {
        org_str.erase(org_str.size() - str4find.size(), str4find.size());
        org_str.insert(org_str.end(), str4replace.begin(), str4replace.end());
        ++find_times;
    }

    return find_times;
}

I update iterator j and i after erase and insert operation, so i think, i and j are not invalid. Anyone can tell me why the end condition: j != org_str.end() is not work?

Aucun commentaire:

Enregistrer un commentaire