strcmp 字符串比较函数,一般形式为strcmp(字符串1,字符串2)。
比较规则:
对两个字符串自左至右逐个字符相比(按ASCII码值大小比较),直到出现不同的字符或遇到‘\0’为止。如果全部字符相同,则认为相等;若出现不相同的字符,则需要对比字母相应的ASCII值,返回类型为:
(1)字符串1=字符串2,返回0
(2)字符串1>字符串2,返回一个正整数
(3)字符串1<字符串2,返回一个负整数。
int my_strcmp(const char *str1, const char *str2)
{
assert(str1 != NULL);
assert(str2 != NULL);
while (*str1 == *str2)
{
if(*str1 == '\0')
return 0;
str1++;
str2++;
}
/*if (*str1 > *str2)
return 1;
else
return -1;*/ //用下面一条语句可以代替上面的if else
return *str1 - *str2;
}
int main()
{
char *str1 = "abqdef";
char *str2 = "abbbbbb";
int ret = my_strcmp(str1, str2);
printf("ret = %d\n", ret);
system("pause");
return 0;
}