Search code examples
c++stdstring

Why is std:string not returning 0 on comparing sub strings of same text?


It's probably some simple oversight, but I'm perplexed on why the second compare doesn't return 0 in the following code:

#include <iostream>

int main()
{
    std::string text =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
    std::string text2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

    int result = text2.compare(text);

    if (result == 0)
    {
        std::cout << "strings same" << std::endl;
    }
    else
    {
        std::cout << "strings NOT same" << std::endl;
    }

    result = text2.compare(0, 10, text);

    if (result == 0)
    {
        std::cout << "strings same" << std::endl;
    }
    else
    {
        std::cout << "strings NOT same" << std::endl;
    }
}

Solution

  • It's because compare function when passed the pos & len parameter, compares the whole of the first string with the second one. The first string is longer than part of the second string which you are comparing.

    If you substring the first string also, then it will return true

    result = text2.compare(0, 10, text, 0, 10);
    

    The above call calls this overload

    int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;
    

    subpos & sublen are pos & length of the first string to compare.