您的位置:首页 > 其它

strcmp和strncmp

2015-08-03 15:14 465 查看
int strcmp(const char *s1,const char *s2);
当s1<s2时,返回为负数

当s1=s2时,返回值= 0

当s1>s2时,返回正数

strncmp,字符串有限比较

int strncmp ( const char * str1, const char * str2, size_t num );

strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。

此函数功能即比较字符串str1和str2的前maxlen个字符。如果前maxlen字节完全相等,返回值就=0;

在前maxlen字节比较过程中,如果出现str1
与str2
不等,则依次比较str1和str2的前n位,

设i(i<n)为两字符串首次的不同位,则返回(str1[i]-str2[i])

eg1.

#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");
elseif(ptr<0)
printf("buffer2 is less than buffer1\n");
ptr=strncmp(buf2,buf3,3);
if(ptr>0)
printf("buffer2 is greater than buffer3\n");
elseif(ptr<0)
printf("buffer2 is less than buffer3\n");
return(0);
}

ouput:
buffer2 is greater than buffer1
buffer2 is less than buffer3eg2.
/*strncmpexample*/
#include<stdio.h>
#include<string.h>
int main()
{
char str[][5]={"R2D2","C3PO","R2A6"};
int n;
puts("Looking for R2 as tromechdroids...");
for(n=0;n<3;n++)
{
if(strncmp(str
,"R2xx",2)==0)
{
printf("found%s\n",str
);
}
//return0;//return位置不对哦
}
return0;
}
ouput:
Looking for R2 as tromechdroids...
foundR2D2
foundR2A6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: