首页 > 编程知识 正文

strcmp和strncmp的区别,strcmp和memcmp

时间:2023-05-04 21:51:49 阅读:205174 作者:3709

strcmp是c语言的基础吧。
可能会有人觉得我这么简单都写个文章来记录,肯定很水。
不过有没有人看都不一定,权当自己记录好了。

SYNOPSIS #include <string.h> int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n);DESCRIPTION The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2. The strncmp() function is similar, except it compares only the first (at most) n bytes of s1 and s2.RETURN VALUE The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

其实看完这部分解释,我还是不怎么懂strcmp的返回值的。

然后我写了个代码验证了一下

#include <stdio.h>#include <string.h> int main(void){int a,aa;char b[] = "b";char c[] = "bc";a = strcmp(b,c); // 看a的返回值是多少aa = !strcmp(b,c);//看经过!a后的值又是多少printf("a = %dn",a);printf("aa = %dn",aa);// 看!到底是什么东西。int k = 10;int j = -12;printf("!k = %d, !j = %dn",!k,!j);return 0;}

经过代码的测试,我发现,如果字符串s1里面对应的ASCII码小于s2的话就会返回负数,等于就会返回0,大于就返回正数。

就好比说s1是b,s2是ba,那么s1-s2 = -97,而97就是a所对应的ASCII的值了。

关于“!”
我一直把它与~搞混。 ~是按位取反,!则不是

通过测试发现,!后面跟着的数,不论正负,只要!过后就是0,
而如果!后面的值是0的话,那么!0就是1了。

注意

这里的大前提是用系统自带的string.h头文件的。

我在一些内核里面找到了string.c
路径:…android4.0.4bspx210v3s_ics_rtm_v14kernellib
打开里面的string.c
找到里面的strcmp的原型如下:

int strcmp(const char *cs, const char *ct){unsigned char c1, c2;while (1) {c1 = *cs++;c2 = *ct++;if (c1 != c2)return c1 < c2 ? -1 : 1;if (!c1)break;}return 0;}

如果使用这个strcmp函数的话就只有1、0、-1三种值了。

· ·

唉,概念都忘得差不多了,但是还是实践出真知。

可能我真的太菜了吧,看见了这篇文章的人也轻点喷。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。