3.模拟实现strcpy
define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
void my_strcpy(char *dst,const char *src)
{
assert(dst);
assert(src);
while(*dst++ == *src++ && *src != '\0')
{
;
}
}
int main()
{
char src[] = "def";
char dst[] = "abc";
my_strcpy(dst,src);
printf("%s",dst);
return 0;
}
4.模拟实现strcat
define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
void my_strcat(char *dst,const char *src)
{
char *tmp = dst;
assert(dst);
assert(src);
while(*tmp != '\0'){tmp++;}
while(*src != '\0')
{
*tmp++ = *src++ ;
}
*tmp = '\0';
}
int main()
{
char src[] = "efg";
char dst[20] = "abcd";
my_strcat(dst,src);
printf("%s\n",dst);
return 0;
}
3.实现strstr
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
//3.实现strstr
char* my_strstr(const char *str1,const char *str2)
{
char *cur =(char *)str1 ;
char *s1,*s2;
assert(str1 != NULL && str2 != NULL);
while(*cur)
{
s1 = cur;
s2 = (char *)str2;
while(*s1 && !(*s2 - *s1))
{
s1++;
s2++;
}
if(!*s2)
return cur;
cur++;
}
return NULL;
}
int main()
{
char src[] = "abcdaeaf";
char *dst = "cde";
if(my_strstr(src,dst))
printf("true!\n");
else
printf("flase!\n");
return 0;
}
4.实现strchr
char* my_strchr(char* str, char a)
{
assert(str);
while(*str != '\0' && *str != a)
{
str++;
}
return *str==a?str:NULL;
}
int main()
{
char arr[] = "abcdef";
char a = 'd';
printf("%s",strchr(arr,a));
return 0;
}
5.实现strcmp
int my_strcmp(char const *p,char const *q)
{
assert(p != NULL && q != NULL);
while(*p == *q)
{
if(*p == '\0')
return 0;
p++;
q++;
}
if(*p>*q)
return 1;
else
return -1;
}
int main()
{
char *p = "abcdef";
char *q = "abcdf";
int ret = my_strcmp(p,q);
if(ret > 0)
printf("前者大于后者!\n");
else if(ret < 0)
printf("前者小于后者!\n");
else
printf("两者一样!\n");
return 0;
}
6.实现memcpy 与memmove相似
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
void my_memcpy(char *dst,char *src,int count)
{
char *p = dst;
char *q = src;
assert(dst);
assert(src);
while(count-- && *q != '\0')
{
*p++ = *q++;
}
while(*p++)
{
;
}
*p = '\0';
}
int main()
{
char *src = "dsd";
char dst[100] = "abcd";
my_memcpy(dst,src,3);
printf("%s\n",dst);
return 0;
}
7.实现memmove为前者的优化
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
void my_memmove(void *dst, void *src, size_t tLen)
{
char *pDst = (char*)dst;
char *pSrc = (char*)src;
assert(pDst != NULL && pSrc != NULL);
if((pDst>pSrc) && (pDst<(pSrc+tLen)))
{
// 特殊处理
char* p = pSrc + tLen - 1;
char* q = pDst + tLen - 1;
while(p >= pSrc)
{
*q-- = *p--;
}
}
else
{
// 不需要特殊处理可直接用memcpy
memcpy(pDst, pSrc, tLen);
}
}
int main()
{
char *src = "dsd";
char dst[100] = "abcdefgh";
my_memmove(dst+3,dst+2,4);
printf("%s\n",dst);
return 0;
}