strcmp和strncmp

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[n]与str2[n]不等,则依次比较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 buffer3
eg2.

/*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[n],"R2xx",2)==0)
{
printf("found%s\n",str[n]);
}
//return0;//return位置不对哦
}
return0;
}
ouput:
Looking for R2 as tromechdroids...
foundR2D2
foundR2A6



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值