在C语言中经常遇到比较两个字符串大小的问题,这里我列出两个常用的比较函数以及它们的具体用法和两者之间的区别。
strcmp函数:
函数原型:int strcmp(const char * s2,const char * s2);
功能:比较字符串s1和字符串s2的大小。
返回值:
s1大于s2,返回值大于零
s1等于s2,返回值等于零
s1小于s2,返回值小于零
特点:两个字符串之间是逐个按照它们的ASIIC大小来比较的,一旦发现其中一个大于或小于另一个时,比较结束,返回一个值,不然就一直比较到’\0’为止。
实例:
#include <stdio.h>
#include <Windows.h>
#include <string.h>
int main()
{
int i = 0;
char *s1 = "Hello bit!";
char *s2 = "Hello bit!";
i = strcmp(s1, s2);
if (i > 0)
{
printf("s1 is greater than s2\n");//s1大于s2
}
else if (0 == i)//变量比较时把变量放右边,这样可以防止出错
{
printf("s1 and s2 are identical\n");//s1等于s2
}
else
{
printf("s1 is less than s2\n");//s1小于s2
}
system("pause");
return 0;
}
memcmp函数:
函数原型:
int memcmp(const void *buf1, const void *buf2, unsigned int count);
功能:比较内存区域buf1和buf2的前count个字节。
返回值:
s1大于s2,返回值大于零
s1等于s2,返回值等于零
s1小于s2,返回值小于零
特点:memcmp函数也是按ASICC码逐个比较,在strcmp的基础上多加了个功能,他能比较字符串中前count字节的大小。如果count == strlen(s1),那就是比较字符串中全部字符。
实例:
#include <stdio.h>
#include <Windows.h>
#include <string.h>
int main()
{
char *s1 = "Hello,bit!";
char *s2 = "Hello,bat!";
int i = 0;
i = memcmp(s1, s2, strlen(s1));
if (i > 0)
{
printf("s1 is greater than s2\n");/*s1大于s2*/
}
else if (0 == i)
{
printf("s1 and s2 are identical\n");/*s1等于s2*/
}
else
{
printf("s1 is less than s2\n");/*s1大于s2*/
}
system("pause");
return 0;
}