The strcmp function allows you to compare to strings to determine their (in)equality.

int
strcmp(const char *s1, const char *s2);

The return value is an integer which indicates whether the first string is greater than, equal to, or less than the second string.

Implementation

The strcmp function is incredibly similar to memcmp except we must stop comparing when we encounter a null-character in s1. We find find that character with the strlen function and use the result, plus 1, to define how many characters to compare. Thus, we can make a call directly to memcmp to do the work for us. All error handling is done in the other functions and strcmp becomes very simple:

return memcmp(s1, s2, strlen(s1) + 1);

It's important to include the + 1 as otherwise an s1 which is a substring of s2 would compare as equal (e.g. strcmp("foo", "foobar")).

Testing

We need to test comparison to/from NULL pointers, to/from empty strings, and all cases of equal, greater than, and less than results. The testing here is slightly different from memcmp as an empty string, "", has a single character in it, the null-character '\0. Therefore we have at least one character to compare and the result should be a non-zero value, assuming the other string has characters in it.

int
strcmpTest(void)
{
    int ret         = 1;
    char pStr1[]    = "This is a Test string";
    char pStr2[]    = "This is a Test string";
    char pStr3[]    = "This is a Lesser string";
    char pStr4[]    = "This is a greater string";
    char *pStr5     = NULL;

    do
    {
        /* NULL s2 pointer */
        if (1 != strcmp(pStr1, pStr5))
        {
            break;
        }

        /* NULL s1 pointer */
        if (1 != strcmp(pStr5, pStr1))
        {
            break;
        }

        /* Empty s2 */
        if (0 >= strcmp(pStr1, ""))
        {
            break;
        }

        /* Empty s1 */
        if (0 <= strcmp("", pStr1))
        {
            break;
        }

        /* Test equality */
        if (0 != strcmp(pStr1, pStr2))
        {
            break;
        }

        /* First string greater than second string */
        if (0 >= strcmp(pStr1, pStr3))
        {
            break;
        }

        /* First string less than second string */
        if (0 <= strcmp(pStr1, pStr4))
        {
            break;
        }

        ret = 0;
    } while (0);

    return ret;
}

Conclusion

memcmp does all the work here while we use strlen to determine the number of characters to be compared, plus one for the null-terminator.

int
strcmp(const char *s1, const char *s2)
{
    return memcmp(s1, s2, strlen(s1) + 1);
}
comments powered by Disqus