strncmp() 函数

来源:互联网 发布:淘宝运营工资待遇 编辑:程序博客网 时间:2024/05/01 23:47
strncmp() 用来比较两个字符串的前n个字符,区分大小写,其原型为:
    int strncmp ( const char * str1, const char * str2, size_t n );

【参数】str1, str2 为需要比较的两个字符串,n为要比较的字符的数目。

字符串大小的比较是以ASCII 码表上的顺序来决定,此顺序亦为字符的值。strncmp()首先将s1 第一个字符值减去s2 第一个字符值,若差值为0 则再继续比较下个字符,直到字符结束标志'\0',若差值不为0,则将差值返回。例如字符串"Ac"和"ba"比较则会返回字符"A"(65)和'b'(98)的差值(-33)。

注意:要比较的字符包括字符串结束标志'\0',而且一旦遇到'\0'就结束比较,无论n是多少,不再继续比较后边的字符。

【返回值】若str1与str2的前n个字符相同,则返回0;若s1大于s2,则返回大于0的值;若s1 若小于s2,则返回小于0的值。

#include<string.h>
#include<stdio.h>
int main(void)
{
char *buf1="aaabbb",*buf2="bbbccc",*buf3="ccc";
int ptr;
ptr=strncmp(buf2,buf1,3);
if(ptr>0)
printf("buffer2 is greater than buffer1\n");
else if(ptr<0)
printf("buffer2 is less than buffer1\n");
ptr=strncmp(buf2,buf3,3);
if(ptr>0)
printf("buffer2 is greater than buffer3\n");
else if(ptr<0)
printf("buffer2 is less than buffer3\n");
return(0);
}

0 0