C標準庫源碼四:strcmp/strncmp

/*
strcmp - compare two strings, returning less than, equal to, or greater than

Purpose:
       Compares two string, determining their lexical order.  Unsigned
       comparison is used.return < 0, 0, or >0, indicating whether the 
       first string is Less than, Equal to, or Greater than the second string.
*/
int strcmp ( const char *s1, const char *s2)
{
    for(;(*s1 == *s2) && (*s1 != '\0');s1++,s2++)
        ;
    return *s1-*s2;
}

​

​​
/* Compare S1 and S2, returning less than, equal to or
   greater than zero if S1 is lexiographically less than,
   equal to or greater than S2.  */

int strcmp(const char *p1, const char *p1)
{
  register const unsigned char *s1 = (const unsigned char *) p1;
  register const unsigned char *s2 = (const unsigned char *) p2;
  unsigned register char c1, c2;

  do
    {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0')
	    return c1 - c2;
    }
  while (c1 == c2);

  return c1 - c2;
}

​​
​
​
​
/*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.
*/
int strncmp(const char *s1, const char *s2, size_t n)
{

    for(;(*s1 != '\0') && (count > 0) && (*s1 == *s2);s1++,s2++,count--)
        ;
    if(count == 0)
        return 0;
    else
        return *s1 - *s2;
}

​​
/* Compare no more than N characters of S1 and S2,
   returning less than, equal to or greater than zero
   if S1 is lexiographically less than, equal to or
   greater than S2.  */
int strncmp(const char *s1, const char *s2 , size_t n)
{
  unsigned register char c1 = '\0';
  unsigned register char c2 = '\0';

  if (n >= 4){
      size_t n4 = n >> 2;
      do{
	      c1 = (unsigned char) *s1++;
	      c2 = (unsigned char) *s2++;
	      if (c1 == '\0' || c1 != c2)
	        return c1 - c2;
	      c1 = (unsigned char) *s1++;
	      c2 = (unsigned char) *s2++;
	      if (c1 == '\0' || c1 != c2)
	        return c1 - c2;
	      c1 = (unsigned char) *s1++;
	      c2 = (unsigned char) *s2++;
	      if (c1 == '\0' || c1 != c2)
	        return c1 - c2;
	      c1 = (unsigned char) *s1++;
	      c2 = (unsigned char) *s2++;
	      if (c1 == '\0' || c1 != c2)
	        return c1 - c2;
      } while (--n4 > 0);
      n &= 3;
  }

  while (n > 0)
  {
      c1 = (unsigned char) *s1++;
      c2 = (unsigned char) *s2++;
      if (c1 == '\0' || c1 != c2)
	    return c1 - c2;
      n--;
  }

  return c1 - c2;
}

 

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