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
当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
相关文章推荐
- 认识与学习 BASH
- linux who命令
- Leetcode 152 Maximum Product Subarray 子数组最大乘积
- 清华人都如此努力,那我们呢?
- Leetcode题目之"Trapping Rain Water"
- 动态内存分配 (Dynamic memory)
- SQL模糊查询中的Like
- Struts2利用iText导出word文档(包含表格)以提供下载
- JS的Document属性和方法(转)
- java 获取未来时间
- linux通过yum安装软件
- MySQL实现ORACLE序列(Sequence)的解决方案
- LVS的基本概念和调度算法
- .NET基础复习一
- C++ const关键字的总结
- MyEclipse配置tomcat(以及端口冲突问题)
- 南阳OJ~~素数距离问题
- 数据结构02_线性表
- IOS之GCD记录
- 新建maven工程