2
\$\begingroup\$

I have a URL in wstring format in C++, e.g.:

http://stackoverflow.com?Country=US&City=Seattle&State=WA

I want to get rid of Country query param from the above string. Country query param can be the first query param or could be the last too.

 wstring ManagementUrl = L"http://stackoverflow.com?Country=US&City=Seattle&State=WA"
    wstring queryParam = L"&Country=US";
    wstring queryParam1 = L"Country=US";

    string::size_type urlLength = ManagementUrl.length();
    string::size_type queryLength = queryParam.length();
    string::size_type queryLength1 = queryParam1.length();

    size_t index = ManagementUrl.find(queryParam);
            if (index != std::wstring::npos)
            {
                wstrLink.erase(index, queryLength);
            }
        size_t index1 = ManagementUrl.find(queryParam1);
            if (index != std::wstring::npos)
            {
                wstrLink.erase(index, queryLength1);
            }  

Is there a better way to do this?

\$\endgroup\$
1
\$\begingroup\$

The problem with your design is that you assume the URL is actually well formed. In my experience (writing web crawlers) we found that greater than 80% of URL's on the web are badly formatted the biggest offender is the first ? that separates the attributes from the target (this was often a &).

Now if you URL is badly formatted like this:

http://stackoverflow.com&Country=US&City=Seattle&State=WA
                   //   ^ Notice the bad format

Your code will break that URL and turn it into:

http://stackoverflow.comUS&City=Seattle&State=WA

Probably not what you want.

Also URL as they pass through systems tend to be normalized (so they can be sorted and all sorts of other things). So your URL may have started of as the above but because it was normalized your query parameters have been re-ordered.

 http://stackoverflow.com?City=Seattle&Country=US&State=WA
                  // Query parameters ordered lexicographically.

Now if you just go and remove the attribute names they may not be in the order you expect.

Now imagine a well formatted URL but with another domain.

http://No.Country=US.For.Old.Men.com?Country=US&City=Seattle&State=WA

Which is a perfectly valid domain. But your code is going to strip out a segment for the domain (and thus make the URL invalid).

http://No..For.Old.Men.com?Country=US&City=Seattle&State=WA
     //  ^^ two dotes consecutively is not valid domain.

Your best bet is to get some already written software for handling URL's there are just too many corner cases for you to write and expect to handle the URL correctly.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.