[Advanced C Language: Get to the bottom of string functions] strcmp function

Highlights of this section:

  • In-depth understanding of the use of strcmp function
  • Learn the simulation implementation of the strcmp function

The following demonstrates a wrong comparison method:

if ("abcdef" == "bcdefg") //这里比较的是两个字符串首字符的地址,而不是字符串的内容

There is no grammatical problem with this comparison, but this code does not compare the contents of the two strings. The reason is that when these two strings are used as expressions, their two values ​​are the address of the first character, so when comparing with the == sign, the comparison is actually the address of the first character of the two strings Equality does not compare the contents of the two strings.


⚡strcmp 

  • This function starts comparing the first character of each string. If they are equal to each
    other, it continues with the following pairs until the characters differ or until a terminating
    null-character is reached.
  • If the first string is greater than the second string, a number greater than 0 is returned.
  • Returns 0 if the first string is equal to the second string.
  • If the first string is less than the second string, returns a number less than 0.

Reminder: The default three return values ​​in the VS system are: -1, 0, 1.


⚡Simulate the strcmp function 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>
#include<assert.h>

int my_strcmp(const char* str1, const char* str2)
{
	assert(str1 && str2);
	while (*str1 == *str2)
	{
		if (*str1 == '\0')
			return 0;
		str1++; 
		str2++;
	}
	//if (*str1 > *str2)
		//return 1;
	//else
		//return -1;
	return *str1 - *str2;
}

int main()
{
	char arr1[] = "abzqw";
	char arr2[] = "abq";
	printf("%d\n", my_strcmp(arr1, arr2));
	return 0;
}

The result of the operation is as follows:


Thank you for reading this blog. It took a long time to create it. Friends think my blog is helpful to you. You may wish to leave your likes and favorites, follow me, and show you a different C language.

98b76a6f4a9c4ca88fd93da1188ac6f9.gif

Guess you like

Origin blog.csdn.net/JX_BC/article/details/129620600