Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ String Compare

Name: Anonymous 2011-09-21 16:58

Sup niggaz. This shit is throwing an exception when it gets to this code in runtime. Any ideas?

- Assume "in" is a string comprised of "http://google.com/derp"
- found is a link found, can be w/e string

As far as I can tell, it explodes on the line where I'm trying to compare the 2 strings, as for some reason the loop is not concatenating the compare string - any idea why that is?


bool isLinkExternal(string in, string found)
{
    string compare = "";
    bool isExternal = false;

    //Get domain of original link
    for (int i = 6; in[i] != '/' ; i++)
    {
        compare += in[i];
    }
   
    //Compare domains of original and found links
    if (found.compare(7,compare.length(),compare) == 0)
        isExternal = true;

    return isExternal;
}


The way I see it, the loop starts at 7 chars in, which excludes the initial "http://". It should then keep going, concatenating each char into the compare string until a slash is found. The last bit is to compare that string to the portion of the string "in" of the same length, starting at the same point (7 chars in, for length of compare)

Name: Anonymous 2011-09-21 18:53

You're passing parameters which are out of bound to the compare member function, you didn't properly read the documentation.

What you're doing is also dangerous by assuming that the strings are at lesat 6/7 characters long. Furthermore, you're doing a bunch of unnecessary copying of data. You are a bad programmer.

Here, I've fixed it for you.


typedef std::pair<size_t, size_t> string_bounds;

inline string_bounds getUrlDomainBounds(std::string const& url) {
    size_t start = (url.compare(0, 6, "http://") == 0) ? 6 : 0;
    size_t end = url.find_first_of('/', start);
    if (end == std::string::npos) {
        end = url.size() - start;
    }
    return std::make_pair(start, end);
}

bool isLinkExternal(std::string const& in, std::string const& found) {
    string_bounds in_bounds = getUrlDomainBounds(in);
    string_bounds found_bounds = getUrlDomainBounds(found);
    return in.compare(in_bounds.first, in_bounds.second, found, in_bounds.first, in_bounds.second) == 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List