一. 头文件声明:
string.h:
#ifndef _STRING_H_
#define _STRING_H_
#include <sys/cdefs.h>
#include <stddef.h>
#include <malloc.h>
extern char* strcpy(char *, const char *);
extern char* strcat(char *, const char *);
......
#endif /* _STRING_H_ */
二.函数实现:
1. strcat
#include <string.h>
char *strcat(char *s, const char *append)
{
char *save = s;
for (; *s; ++s);
while ((*s++ = *append++) != '/0');
return(save);
}
2. strcpy
#include <string.h>
char *strcpy(char *to, const char *from)
{
char *save = to;
for (; (*to = *from) != '/0'; ++from, ++to);
return(save);
}
3. strlen
size_t strlen(const char *str)
{
const char *s;
for (s = str; *s; ++s)
;
return (s - str);
}
4. strcmp
int strcmp(const char *s1, const char *s2)
{
while (*s1 == *s2++)
if (*s1++ == 0)
return (0);
return (*(unsigned char *)s1 - *(unsigned char *)--s2);
}
5. strstr
char *strstr(const char *s, const char *find)
{
char c, sc;
size_t len;
if ((c = *find++) != 0) {
len = strlen(find);
do {
do {
if ((sc = *s++) == 0)
return (NULL);
} while (sc != c);
} while (strncmp(s, find, len) != 0);
s--;
}
return ((char *)s);
}
6. strncpy
char *strncpy(char *dst, const char *src, size_t n)
{
if (n != 0) {
char *d = dst;
const char *s = src;
do {
if ((*d++ = *s++) == 0) {
/* NUL pad the remaining n-1 bytes */
while (--n != 0)
*d++ = 0;
break;
}
} while (--n != 0);
}
return (dst);
}
7. strncmp
int strncmp(const char *s1, const char *s2, size_t n)
{
if (n == 0)
return (0);
do {
if (*s1 != *s2++)
return (*(unsigned char *)s1 - *(unsigned char *)--s2);
if (*s1++ == 0)
break;
} while (--n != 0);
return (0);
}
8. strncat
char *strncat(char *dst, const char *src, size_t n)
{
if (n != 0) {
char *d = dst;
const char *s = src;
while (*d != 0)
d++;
do {
if ((*d = *s++) == 0)
break;
d++;
} while (--n != 0);
*d = 0;
}
return (dst);
}