#include
char *strcat(char *str1, const char *str2);
size_t strlen(char *str);
char *strcpy(char *to, const char *from);
int strcmp(const char *str1, const char *str2);
int main(void)
{
char str1[100] = "hello";
char str2[100] = ",world";
strcat(str1, str2);
printf("str1 is \"%s\".\n", str1);
printf("the length of \"%s\" is %d.\n", str1, strlen(str1));
char from[100] = "hell0";
char to[100] = {0};
strcpy(to, from);
printf("to is \"%s\"\n", to);
char s1[] = "abc";
char s2[] = "abc";
char s3[] = "cba";
printf("%d\n", strcmp(s1, s1));
printf("%d\n", strcmp(s1, s3));
printf("%d\n", strcmp(s3, s1));
return 0;
}
/**
* 函数将字符串str2连接到str1的末端,并返回指针str1。
* @param str1
* @param str2
* @return str1指针
*/
char *strcat(char *str1, const char *str2 )
{
char *p = str1;
while (*p != '\0')
p++;
while ((*p++ = *str2++) != '\0');
return str1;
}
/**
* 函数返回字符串str的长度( 即空值结束符之前字符数目)。
* @param str
* @return 返回字符串str的长度
*/
size_t strlen(char *str)
{
int len = 0;
while (*str)
{
str++;
len++;
}
return len;
}
/**
* 复制字符串from 中的字符到字符串to,包括空值结束符。返回值为指针to。
* @param to
* @param from
* @return 指针to
*/
char *strcpy(char *to, const char *from)
{
char *p = to;
while ((*to++ = *from++) != '\0');
return p;
}
/**
* 比较字符串str1 and str2
* @param str1 [description]
* @param str2 [description]
* @return
* = = : str1 = str2
* > 0 : str1 > str2
*/
int strcmp(const char *str1, const char *str2)
{
while (*str1 && *str2 && *str1 == *str2)
{
str1++;
str2++;
}
return *str1 - *str2;
}
没考虑效率。功能已经实现了。