On the realization of strcmp()

strcmp string comparison

  1. The first string is greater than the second string, and the return value is greater than 0.

  2. The first string is equal to the second string, and the return value is equal to 0.

  3. The third string is less than the second string, and the return value is less than 0.

  4. String comparison is to compare character by character, by comparing the ascll code value, if it is not waiting, return directly, if it is equal, compare the next character, until a string is longer than nothing, at this time which string is longer, which string is bigger .

  5. Function implementation

     int my_strcmp(const char* str1, const char* str2)
     {
     	while (*str1 && *str2)
     	{
     		if (*str1 > *str2)
     		{
     			return 1;
     		}
     		else if (*str1 < *str2)
     		{
     			return - 1;
     		}
     		else
     		{
     			str1++;
     			str2++;
     		}
     	}
     	if (*str1)
     	{
     		return 1;
     	}
     	else if (*str2)
     	{
     		return -1;
     	}
     	return 0;
     }
    

      After the execution of the first while is completed, one of the two strings has been compared. At this time, it is judged which string is empty first, who is empty first and who is smaller, and one is empty, then it is equal.

Guess you like

Origin blog.csdn.net/weixin_43580319/article/details/112140920