Large collection of comparison functions: strcmp, strncmp, memcmp

Foreword:

Then play music and dance, let’s continue to look at string functions and memory functions. What I want to talk about today is a large collection of comparison functions, not much to say, open your eyes! ! !

strcmp function:

What is the strcmp function?

strcmp is string compare, which translates to string comparison. As the name implies, it is a function used to compare the size of strings.

Its return type is int. When the former is greater than the latter, it returns 1, when the former is equal to the latter, it returns 0, and if the former is less than the latter, it returns -1. There are 2 parameters, a source string and a target string. Because the two are only compared and not modified, they are modified with const to prevent them from being changed. Its header file is string.h.

How to use the strcmp function?

See the actual operation:

Advanced knowledge of strcmp:

1. About the comparison of strings

In C language, there is no way to directly compare two strings. For example, the above is an error demonstration. The string “abcdefg” or arr1/arr2 are both equal to the address of the first element of the string. Obviously, the two addresses are not the same, so the output is not equal. In this case, you have to use the strcmp function for comparison.

In this example, it is equal. The reason is that both p and q are constant strings, and both p and q point to the same memory (address of abcdefg), so the addresses are naturally the same. So equals.

2. The return value of strcmp

Through the above example, we know that when two strings are equal, the return value is 0. So if they are not equal, what is the return value?

Is whoever grows older?

Through the above examples, we can find that the comparison of strcmp is not as simple as whoever is older. Instead, it depends on the size of the first different character.

Conclusion: strcmp essentially compares the size of the ASCII code value of the first different digit.

For example two strings A, B. If all corresponding characters are the same, then strcmp(A,B)=0, if the ASCII code value of the first digit is different, A is greater than B, then no matter how long B is behind, it will return 1. Otherwise return -1.

Just like the last example above, although arr2 is just c\0, strcmp(arr1,arr2)=-1.

Custom strcmp function:

Code self-fetching:

int my_strcmp(const char* str1, const char* str2)
{
    assert(str1 & amp; & amp; str2);//Prevent str1 and str2 from having null pointers
    while (*str1 == *str2)
    {
        if (*str1 == '\0')//Both pointers have encountered \0 and have not jumped out of the loop, indicating that the two strings are equal
        {
            return 0;
        }
        str1++;
        str2++;
    }
    if (*str1 > *str2)//Jump out of the loop when encountering the first different bit, so you can directly compare *str1 and *str2
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

strncmp function:

What is the strncmp function?

The return value of strncmp is the same as that of strcmp, but there is an extra parameter n. Its relationship with strcmp is like the relationship between strncpy and strcpy functions, there is an extra n to control the number of bytes. Naturally, strncmp is used to compare the size of the first n bytes (the first n characters, because the character type size is 1 byte in 32-bit compilers) of two strings. The header file is also string.h

How to use the strncmp function?

See examples:

Special case:

What if the number of bytes to compare exceeds one of the string lengths?

When the number of bytes to compare exceeds the length of the string, a \0 (whoever’s) is encountered during a byte-by-byte comparison stops the comparison. In the above two examples the first one is 1 because the ASCII code value of 0 is greater than the ASCII code value of \0.

Custom strncmp function:

Code self-fetching:

int my_strncmp(const char* str1, const char* str2, size_t num)
{
    int n = 1;
    while (*str1 == *str2)
    {
        if (*str1 == 0 || n == num)
        {
            return 0;
        }
        str1++;
        str2++;
        n + + ;
    }
    if (*str1 > *str2)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

The principle is very similar to the customization of the strcmp function, nothing more than adding n to control the number of comparisons.

memcmp function:

What is the memcmp function?

strcmp can only compare string data, which has relatively large limitations. So when comparing other data, we use the memcmp function.

memcmp, that is, memory compare, translates to memory comparison. Its return type is int, with 3 parameters, buf1 and buf2 are of void* type because the person who defines the function does not know what kind of data the user uses it to compare, so it is defined as void* to accept. The memcmp function also uses count to control the number of bytes compared. The header file is memory.h or string.h

How to use the memcmp function?

As always, talking on paper is not enough, let’s see it in practice:

Memcmp advanced knowledge:

1. Is the comparison method of memcmp the same as that of strcmp?

It is obviously different. In Example 1, it seems to be the same as strcmp. The first different bit is exactly 2<1 and outputs -1, but in Example 2, the first different bit, that is, 1048592 is obviously greater than 4112. In theory, it should output 1 but it is Output -1, why is this?

Parse:

in conclusion:

The core of memcmp and strcmp comparison is the first different bit (compared byte by byte), not the first different element.

2. What if when comparing integer data, the compared bytes are not the integer times of the data?

In this program we compare 21 bytes of arr1 and arr2, but still output 1, why?

Parse:

Conclusion: Therefore, when using the memcmp function to compare data of more than one byte, pay special attention to the little-endian storage mode or the big-endian storage mode.

3. What happens when the number of bytes in memcmp exceeds a certain memory block during comparison?

Because arr2 is only 4 bytes in size, it is obviously not enough to compare it with arr1 at 20 bytes, so the system will report a warning. Although the comparison is also -1, it is very unsafe to do so.

in conclusion:

When using the memcmp function, it should be noted that the number of bytes compared cannot exceed the size of the compared memory.

Custom memcmp function:

Code self-fetching:

#include <assert.h>
int my_memcmp(const void* ptr1, const void* ptr2, size_t num)
{
    assert(ptr1 & amp; & amp; ptr2);
    // force type conversion
    char* ptr11 = (char*)ptr1;
    char* ptr22 = (char*)ptr2;
    while (*ptr11 == *ptr22 & amp; & amp; num--)
    {
        ptr11++;
        ptr22++;
    }
    if (*ptr11 > *ptr22)
    {
        return 1;
    }
    else if (*ptr11 < *ptr22)
    {
        return -1;
    }
    return 0;
}

Since a byte-by-byte comparison is required, we directly cast it to a char* type to achieve a byte-by-byte comparison.

Conclusion:

Summary: For character data comparison, use strcmp and strncmp, professional counterparts. Others use memcmp.

Ok hot, the big collection of comparison functions is over here!

What you read is what you earn! I hope everyone has gained something, I will be very happy (●ˇ?ˇ●)

The green hills remain unchanged, and the green waters flow forever. See you next time! ! !

It’s still the same old saying: the road is long and long, and I will search for it up and down! ! !