strncmp源碼

//

//  main.cpp

//  AUTO_PRO

//

//  Created by yanzhengqing on 12-12-11.

//  Copyright (c) 2012 yanzhengqing. All rights reserved.

//


#include <iostream>

using namespace std;


/***

 *int strncmp(first, last, count) - compare first count chars of strings

 *

 *Purpose:

 *       Compares two strings for lexical order.  The comparison stops

 *       after: (1) a difference between the strings is found, (2) the end

 *       of the strings is reached, or (3) count characters have been

 *       compared.

 *

 *Entry:

 *       char *first, *last - strings to compare

 *       unsigned count - maximum number of characters to compare

 *

 *Exit:

 *       returns <0 if first < last

 *       returns  0 if first == last

 *       returns >0 if first > last

 *

 *Exceptions:

 *

 *******************************************************************************/



/////////////////////////////////////////////////////////////////////////////////

/*說明:

  1. __cdecl C Declaration的縮寫(declaration,聲明),表示C語言默認的函數調用方法:所有參數從右到左依次入棧,這些參數由調用者清除,稱爲手動清棧。被調用函數不會要求調用者傳遞多少參數,調用者傳遞過多或者過少的參數,甚至完全不同的參數都不會產生編譯階段的錯誤。

  2. 基於字典順序比較兩個字符串,最多比較n個字節

  3.  按照ANSI(American National Standards Institute)標準,不能對void指針進行算法操作,即不能對void指針進行如p++的操作,所以需要轉換爲具體的類型指針來操作,例如char *。(引用網友的結論)

  4.  size_t 類型定義在cstddef頭文件中,該文件是C標準庫的頭文件stddef.hC++版。它是一個與機器相關的unsigned類型,其大小足以保證存儲內存中對象的大小。

*/


int __cdecl strncmp (

                    const char * first,

                    const char * last,

                    size_t count

                     )

{

   if (!count)

       return(0);

    

   while (--count && *first && *first == *last)

    {

        first++;

        last++;

    }

    

   return( *(unsignedchar *)first - *(unsignedchar *)last );

}



int main()

{

   int p = 0;

   const char src[50] ="blog.csdn.con";

    constchar brc[50] ="blog.csdn.net/barry_yan";

   cout<<src<<endl;

   cout<<brc<<endl;

    p =strncmp(src,brc,strlen(src)+1);


   cout<<p<<endl;


   return 0;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章