Large collection of comparison functions: strcmp, strncmp, memcmp

Foreword:

After playing music and dancing, we continue to look at string functions and memory functions. Today I’m going to talk about a large collection of comparison functions. Without further ado, let’s have fun! ! !

strcmp function:

What is strcmp function?

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

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

How to use strcmp function?

See it in action:

Advanced knowledge of strcmp:

1. Comparison of strings

In C language, two strings cannot be directly compared. For example, the above is an error demonstration. The string "abcdefg" or arr1/arr2 is 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.

But in this case, they are equal. The reason is that p and q are both constant strings, p and q both point to the same memory (the address of abcdefg), and the addresses are naturally the same. So equals.

2.The return value of strcmp

From 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?

Whoever is taller will be bigger?

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

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

For example, two strings A and B. If all the 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 it is after B, 1 will be returned. Otherwise it returns -1.

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

Custom strcmp function:

Code self-pickup:

int my_strcmp(const char* str1,const char* str2)
{
    assert(str1 && str2);//防止str1和str2存在空指针的情况
    while (*str1 == *str2)
    {
        if (*str1 == '\0')//两个指针都遇到\0了还没跳出循环,说明两个字符串都相等
        {
            return 0;
        }
        str1++;
        str2++;
    }
    if (*str1 > *str2)//在遇到第一位不同位时跳出循环,所以可以直接比较*str1和*str2
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

strncmp function:

What is strncmp function?

The return value of strncmp is the same as strcmp, but there are one more n parameters. Its relationship with strcmp is the same as the relationship between strncpy and strcpy functions, both with 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 a 32-bit compiler) of two strings. The header file is also string.h

How to use strncmp function?

See examples:

Special case:

What if the number of bytes to be compared exceeds the length of one of the strings?

When the number of bytes to be compared exceeds the length of the string, and \0 (no matter whose) is encountered during the byte-by-byte comparison, the comparison will stop. 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-pickup:

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, except that n is added to control the number of comparisons.

memcmp function:

What is memcmp function?

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

memcmp, memory compare, translates to memory comparison. Its return type is int, with 3 parameters, buf1 and buf2 are of type void* because the person who defined 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 memcmp function?

As always, talking on paper won’t work, let’s look at practice:

Advanced knowledge of memcmp:

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

It is obviously different. In the first example, it looks the same as strcmp. The first different bit is exactly 2<1 and the output is -1. However, in the second example, the first different bit, 1048592, is obviously larger than 4112. In theory, it should output 1 but it does not. -1 is output, why is this?

Analysis:

in conclusion:

The kernels compared by memcmp and strcmp are the first different bits (compared byte by byte), not the first different elements.

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

In this program, we compare the 21 bytes of arr1 and arr2, but 1 is still output. Why is this?

Analysis:

Conclusion: Therefore, when using the memcmp function to compare data that exceeds one byte, special attention should be paid to the little-endian storage mode or the big-endian storage mode.

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

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

in conclusion:

When using the memcmp function, be careful that the number of bytes compared cannot exceed the size of the comparison memory.

Custom memcmp function:

Code self-pickup:

#include<assert.h>
int my_memcmp(const void* ptr1, const void* ptr2, size_t num)
{
    assert(ptr1 && ptr2);
    //强制类型转化
    char* ptr11 = (char*)ptr1;
    char* ptr22 = (char*)ptr2;
    while (*ptr11 == *ptr22 && num--) 
    {
        ptr11++;
        ptr22++;
    }
    if (*ptr11 > *ptr22)
    {
        return 1;
    }
    else if (*ptr11 < *ptr22)
    {
        return -1;
    }
    return 0;
}

Since we need to compare byte by byte, we directly cast it to the char* type to achieve byte by byte comparison.

Conclusion:

Summary: When comparing character data, use strcmp and strncmp, which are professional counterparts. Others use memcmp.

Ok spicy, this is the end of the large collection of comparison functions!

Read it and earn it! I hope you all gain something, I will be very happy (●ˇ∀ˇ●)

The green mountains remain unchanged and the green water flows forever. See you next time! ! !

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

Guess you like

Origin blog.csdn.net/qq_74292674/article/details/129736389