GNU LIBC源代码学习之strcmp
2016-03-31 12:06
337 查看
比較两个字符串
我的代码块
这里,上面的方法。不可靠,没有明白的内在逻辑。
看看源代码
要比較s1和s2的每个字节的大小,则,两者比較,最简单的分类就是相等和不相等,在相等的时候继续,不相等时。马上计算返回。
至于
const unsigned char s1 = (const unsigned char ) p1;
const unsigned char s2 = (const unsigned char ) p2;
这样转换的妙处,未能体会
我的代码块
#include <string.h> int my_strcmp(const char* s1,const char * s2) { if((s1==NULL)||(s2==NULL)) return 0; while(1) { if((*s1=='\0')||(*s2=='\0')) break; if(*s1>*s2) return 1; if(*s1<*s2) return -1; s1++; s2++; } //if(*s1==*s2=='\0') // return 0; if(*s1=='\0'&&*s2=='\0') return 0; if(*s1>*s2) return 1; else return -1; } int main() { char* a="abcdef"; char* b="abcdef"; my_strcmp(a,b); return 0; }
这里,上面的方法。不可靠,没有明白的内在逻辑。
看看源代码
/* Copyright (C) 1991-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <string.h> #undef strcmp /* Compare S1 and S2, returning less than, equal to or greater than zero if S1 is lexicographically less than, equal to or greater than S2. */ int strcmp (const char *p1, const char *p2) { const unsigned char *s1 = (const unsigned char *) p1; const unsigned char *s2 = (const unsigned char *) p2; unsigned char c1, c2; do { c1 = (unsigned char) *s1++; c2 = (unsigned char) *s2++; if (c1 == '\0') return c1 - c2; } while (c1 == c2); return c1 - c2; }
要比較s1和s2的每个字节的大小,则,两者比較,最简单的分类就是相等和不相等,在相等的时候继续,不相等时。马上计算返回。
至于
const unsigned char s1 = (const unsigned char ) p1;
const unsigned char s2 = (const unsigned char ) p2;
这样转换的妙处,未能体会
相关文章推荐
- Spring框架:Spring容器具体解释
- java 中 Thread.sleep方法的含义
- QT多国语言动态切换常见例子
- java.sql.Exception:setString 只能处理少于 32766 个字符的字符串
- 内容URI及自定义ContentProvider重写方法
- Java并发:ThreadLocal详解
- asp.net获取session进行简单的用户登录验证。
- Eclipse:打包时出现Conversion to Dalvik format failed with error 1
- Java 实现导出excel表 POI
- php中使用GD库做验证码
- asp.net MVC利用自定义ModelBinder过滤关键字的方法(附demo源码下载)
- maven强制更新 eclipse 操作
- pthread编程基础
- C# 发送邮件3
- Spring中多配置文件及引用其他bean的方式
- Java - 经典代码题
- Java Method的invoke简单理解
- 支持向量机(SVM)算法的matlab的实现
- <td width="172" rowspan="2" align="center"><?php echo "<img src=\"$icon\">";?></td>
- C++中数字与字符串之间的转换,别人的,