几个常见字符串处理函数
/* *
* str开头的函数部分
* In the following functions,
* variables s and t are of type char *;
* cs and ct are of type const char *;
* n is of type size_t;
* and c is an int converted to char.
*/
/* strcpy - copy string ct to string s,
including '\0'; return s. */
char *strcpy(char *s, const char *ct)
{
char *tmp = s;
while ((*tmp++ = *ct++) != '\0')
/* nothing */;
return s;
}
/* strcat - concatenate string ct to end of string s;
return s. *
char *strcat(char * s, const char * ct)
{
char *tmp = s;
while (*tmp)
tmp++;
while ((*tmp++ = *ct++) != '\0')
/* nothing */;
return s;
}
/* strcmp - compare string cs to string ct,
return <0 if cs<ct, 0 if cs==ct, or >0 if cs>ct. */
int strcmp(const char *cs,const char *ct)
{
register signed char __res;
while (1) {
if ((__res = *cs - *ct++) != 0 || !*cs++)
break;
}
return __res;
}
/* strlen - return length of cs. *
size_t strlen(const char *cs)
{
const char *tmp;
for (tmp = cs; *tmp != '\0'; ++tmp)
/* nothing */;
return tmp - cs;
}
/**
* mem开头的函数部分
* The mem... functions are meant for manipulating
* objects as character arrays; the intent is an
* interface to efficient routines.
* In the following functions, s and t are of type void *;
* cs and ct are of type const void *; n is of type size_t;
* and c is an int converted to an unsigned char.
*/
/* memcpy - copy n characters from ct to s, and return s. */
void *memcpy(void *s, const void *ct, size_t n)
{
char *dst = (char *)s, *src = (char *)ct;
while (n--)
*dst++ = *src++;
return s;
}
/* memmove - same as memcpy except that it works even
if the objects overlap. */
void *memmove(void *s, const void *ct, size_t n)
{
char *dst, *src;
if (s <= ct) {
dst = (char *)s;
src = (char *)ct;
while (n--)
*dst++ = *src++;
} else {
dst = (char *)s + n;
src = (char *)ct + n;
while (n--)
*--dst = *--src;
}
return s;
}
/* memcmp - compare the first n characters of cs with ct;
return as with strcmp. */
int memcmp(const void *cs, const void *ct, size_t n)
{
const unsigned char *su1, *su2;
signed char res = 0;
for( su1 = cs, su2 = ct; 0 < n; ++su1, ++su2, n--)
if ((res = *su1 - *su2) != 0)
break;
return res;
}
/* memset - place character c into first n
characters of s, return s. */
void *memset(void *s, char c, size_t n)
{
char *xs = (char *)s;
while (n--)
*xs++ = c;
return s;
}