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.
Return Value
Returns an integral value indicating the relationship between the strings:
return value | indicates |
---|---|
<0 | the first character that does not match has a lower value in ptr1 than in ptr2 |
0 | the contents of both strings are equal |
>0 | the first character that does not match has a greater value in ptr1 than in ptr2 |
通过查看文档,我们已经大致了解了strcmp函数的用途。它是一个字符串比较函数,用于比较两个字符串是否相等。比较规则是:两个指针分别指向两个字符串的首部,然后开始根据ascii码进行比较,如果相等,则指针移动,接着比较下一个字符;直到连个字符不相等或者是其中一个已经到了\0,则比较结束。
代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int Strcmp(const char*str1, const char*str2)
{
assert(str1);
assert(str2);
int ret=0;
//注意这里的条件不能只是*str1==*str2,因为如果两个指针都走到了‘\0’,则还是满足循环条件,指针又进行了移动,导致后面结果出错
//而这时其实两个字符串比较结果已经出来,是相等的。所以一定还要要添加条件“其中一个指针已经到达\0"
while (*str1 == *str2&&*str1!='\0')
{
str1++;
str2++;
}
if (*str1 > *str2)
{
ret = 1;
}
else if (*str1 < *str2)
{
ret = -1;
}
return ret;
}
int main()
{
char*str1 = "adc";
char*str2 = "ad";
int ret = Strcmp(str1, str2);
printf("%d", ret);
system("pause");
return 0;
}