几个重点强调一下:
(1)注意使用assert;
(2)strcat 和 strcpy最后注意赋值'\0';
(3)strcpy注意内存覆盖的情况;
(4)strcmp中:while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0');???为什么要转换类 型;
(5)strstr函数中返回的类型也要为const。
#include<stdio.h>
#include<assert.h>
#include<string.h>
const char* strstr(const char *s1, const char *s2)
{
assert(s1 != NULL && s2 != NULL);
const char *tmp = s1;
for(; *tmp != '\0'; ++tmp)
{
const char *result = tmp;
const char *tmp1 = s2;
while(*result == *tmp1 && *tmp1 != '\0')
{
++result; //++tmp;
++tmp1;
}
if(*tmp1 == '\0')
return tmp; //return result
}
return NULL;
}
char *strcat(char *dest, const char *src)
{
assert(dest != NULL || src != NULL);
char *tmp = dest;
while(*tmp != '\0')
{
++tmp;
}
while(*src != '\0')
{
*tmp = *src;
++tmp;
++src;
}
*tmp = '\0';
return dest;
}
char *strcpy(char *dest, const char *src)
{
assert(dest != NULL || src != NULL);
int length = strlen(src);
char *result = dest;
if(dest < src || src + length < dest)
{
while(*src != '\0')
{
*dest = *src;
++src;
++dest;
}
*dest = '\0';//不能忘了
}else
{
src = src + length - 1;
dest = dest + length;
*dest = '\0';
--dest;
for(int i = 0; i < length; ++i)
{
*dest = *src;
--src;
--dest;
}
}
return result;
}
int strcmp(const char *s1, const char *s2)
{
assert(s1 != NULL || s2 != NULL);
int ret = 0;
while(!(ret = *(unsigned char *)s1 - *(unsigned char *)s2) && *s2 != '\0')
{
++s1;
++s2;
}
if(ret < 0)
return -1;
else if(ret > 0)
return 1;
return ret;
}
int main()
{
char s1[] = "shui huai li";
char s2[] = "huai";
char s3[] = "i am the best";
char s4[] = "sorry";
char s6[] = "sorryhe";
char s5[] = "hello world";
const char *result = strstr(s1, s3);
if(result)
printf("%s\n", result);
else
printf("i am sorry!!!\n");
//printf("%s\n", strcat(s1, s5));
//printf("%s\n", strcpy(s2, s1));
//printf("%d\n", strcmp(s4, s6));
return 0;
}