【C语言】strcmp模拟实现

Introduction

strcmp
int strcmp ( const char * str1, const char * str2 );
Compare two strings
Compares the C string str1 to the C string str2.

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.

This function performs a binary comparison of the characters. For a function that takes into account locale-specific rules, see strcoll.

Parameters
str1
C string to be compared.
str2
C string to be compared.

【C语言】strcmp模拟实现_第1张图片

source:https://cplusplus.com/reference/cstring/strstr/?kw=strstr

Realization

int my_strcmp(
	const char* str1, 
	const char* str2
	)
{
     
	assert(str1 && str2);
	int ret = 0;
	while ((ret = (*str1 - *str2)) == 0 && *str1)
		{
     
			str1++;
			str2++;
		}
	return -(ret < 0) + (ret > 0);
}

你可能感兴趣的