GNU LIBC源碼學習之strcmp

來源:互聯網
上載者:User

標籤:源碼

比較兩個字串

My Code塊

#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.  */intstrcmp (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;
這樣轉換的妙處,未能體會

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

GNU LIBC源碼學習之strcmp

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.