C標準庫string.h源碼三strcat/strncat

​
/*
char *strcat(dst, src) - concatenate (append) one string to another

Purpose:
       Concatenates src onto the end of dest.  Assumes enough
       space in dest.
*/

char * strcat (char * dst, const char * src)
{
    char * cp = dst;

    while( *cp )
        ++cp;           /* Find end of dst */
    while( *cp++ = *src++ )
       ;               /* Copy src to end of dst */
    return( dst );
}

​​
/* Append SRC on the end of DEST.  */
char *strcat(char *dest,const char *src)
{
  register char *s1 = dest;
  register const char *s2 = src;
  register char c;

  /* Find the end of the string.  */
  do
    c = *s1++;
  while (c != '\0');

  /* Make S1 point before the next character*/
  s1 -= 2;

  do
    {
      c = *s2++;
      *++s1 = c;
    }
  while (c != '\0');

  return dest;
}


/*
char *strncat(front, back, count) - append count chars of back onto front

Purpose:
       Appends at most count characters of the string back onto the
       end of front, and ALWAYS terminates with a null character.
       If count is greater than the length of back, the length of back
       is used instead.  (Unlike strncpy, this routine does not pad out
       to count characters).
*/

char *strncat (char *front, const char *back, unsigned count)
{
    char *start = front;

    while (*front++)
        ;
    front--;

    while (count--)
        if ((*front++ = *back++) == '\0')
            return(start);
    *front = '\0';
    return(start);
}

​​
char *strncat(char *s1, const char *s2,size_t n)
{
  register char c;
  char *s = s1;

  /* Find the end of S1.  */
  do
    c = *s1++;
  while (c != '\0');

  /* Make S1 point before next character, so we can increment
     it while memory is read (wins on pipelined cpus).  */
  s1 -= 2;

  if (n >= 4){
      size_t n4 = n >> 2;
      do{
	      c = *s2++; *++s1 = c;
	      if (c == '\0')
	        return s;

	      c = *s2++;*++s1 = c;
	      if (c == '\0')
	        return s;

	      c = *s2++;*++s1 = c;
	      if (c == '\0')
	        return s;

	      c = *s2++;*++s1 = c;
	      if (c == '\0')
	        return s;
	    } while (--n4 > 0);
    n &= 3;
 }

  while (n > 0)
  {
      c = *s2++;*++s1 = c;
      if (c == '\0')
	    return s;
      n--;
  }

  if (c != '\0')
    *++s1 = '\0';

  return s;
}

​

 

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