jeudi 2 juin 2016

std::string replace "&" with "&"

I have to replace all occurrences of only "&" with "&" in a string. But i have to skip it if "&" is followed by a ";" i.e if "&" or "&engrave;" etc. is there it is not to be modified.

I have written the following code link and it seems to be working as well but in this I m doing to many comparisons I think, is there a better way do it , I can use boost or c++11.

#include <string>
#include <iostream>

int main()
{
    std::string str = "An R&D string with one more R&amp;D here and S&D or T&engrave; Some More T&D and &amp;&engrave; and R&&D";
    std::cout<<"original string is : "<<str<<std::endl;
    int index = 0;
    while(1)
    {
        std::string::size_type n = str.find("&",index);
        if(n == std::string::npos)
            break;
        std::string sub = str.substr(n+1, 10);
        std::string::size_type m = sub.find("&");
        std::string::size_type b = sub.find(";");
        if(m != std::string::npos && m<b)
        {
            auto temp = sub.substr(0,m-1);
            sub = temp;
        }
        if(sub.find(";") == std::string::npos)
        {
            str.replace(n, 1, "&amp;");
        }
         index = n+1;
    }
    std::cout<<"changed string is : "<<str<<std::endl;
}

Aucun commentaire:

Enregistrer un commentaire