天天看點

C語言之memcmp函數

【FROM MSDN && 百科】

原型:  int memcmp(const void *buf1, const void *buf2, unsigned int count);

#include<string.h>

比較記憶體區域buf1和buf2的前count個位元組。此函數是按位元組比較。

Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not。

Notice that, unlike strcmp, the function does not stop comparing after finding a null character.

對于memcmp(),如果兩個字元串相同而且count大于字元串長度的話,memcmp不會在\0處停下來,會繼續比較\0後面的記憶體單元,如果想使用memcmp比較字元串,要保證count不能超過最短字元串的長度,否則結果有可能是錯誤的。

DEMO:

[cpp]  view plain  copy

  1. //#define FIRST_DEMO  
  2. #define MYMEMCMP  
  3. #ifdef FIRST_DEMO  
  4. #include <stdio.h>  
  5. #include <conio.h>  
  6. #include <string.h>  
  7. int main(void)  
  8. {  
  9.     char *s1="Hello, Programmers!";  
  10.     char *s2="Hello, Programmers!";  
  11.     int r;  
  12.     r=memcmp(s1,s2,50);  
  13.     if (!r)  
  14.     {  
  15.         printf("s1 and s2 are identical!\n");  
  16.     }  
  17.     else if (r<0)  
  18.     {  
  19.         printf("s1 less than s2\n");  
  20.     }  
  21.     else  
  22.     {  
  23.         printf("s1 greater than s2\n");  
  24.     }  
  25.     getch();  
  26.     return 0;  
  27. }  
  28. #elif defined MYMEMCMP  
  29. #include <stdio.h>  
  30. #include <conio.h>  
  31. #include <string.h>  
  32. int mymemcmp(const void *buffer1,const void *buffer2,int ccount);  
  33. void Print(char *str1,char *str2,int t);  
  34. int main(void)  
  35. {  
  36.     char *str1="hel";  
  37.     char *str2="hello";  
  38.     Print(str1,str2,mymemcmp(str1,str2,3));  
  39.     Print(str2,str1,mymemcmp(str2,str1,3));  
  40.     Print(str2,str2,mymemcmp(str2,str2,3));  
  41.     getch();  
  42.     return 0;  
  43. }  
  44. int mymemcmp(const void *buffer1,const void *buffer2,int count)  
  45. {  
  46.     if (!count)  
  47.     {  
  48.         return 0;  
  49.     }  
  50.     while(count && *(char *)buffer1==*(char *)buffer2)  
  51.     {  
  52.         count--;  
  53.         buffer1=(char *)buffer1-1;  
  54.         buffer2=(char *)buffer2-1;  
  55.     }  
  56.     return (*((unsigned char *)buffer1)- *((unsigned char *)buffer2));  
  57. }  
  58. void Print(char *str1,char *str2,int t)  
  59. {  
  60.     if (t>0)  
  61.     {  
  62.         printf("\n%s Upper than %s \n",str1,str2);  
  63.     }  
  64.     else if(t<0)  
  65.     {  
  66.         printf("\n%s Lower than %s \n",str1,str2);  
  67.     }  
  68.     else  
  69.     {  
  70.         printf("\n%s equal %s \n",str1,str2);  
  71.     }  
  72. }  
  73. #endif  
C語言之memcmp函數
memcmp按位元組比較,可以設定比較的位數
strcmp按字元比較,隻能比較整個字元串
都是用ASCII碼進行比較,效率在數量級上不會相差太大的