1.模拟实现strcpy
//模拟实现字符串拷贝函数strcpy运行结果:
#include <stdio.h>
#include <stdlib.h>
char* my_strcpy(char* dest,const char* src)
{
char* ch = dest;
while(*dest++ = *src++)//*(p++)解引用操作符、后置++,结合方向自右向左
;
return ch;
}
int main()
{
int i = 0;
char arr[20];
char* ret = my_strcpy(arr,"hello world");
printf("%s\n",ret);
system("pause");
return 0;
}
2.模拟实现strcmp
//模拟实现字符串比较函数strcmp运行结果:
#include <stdio.h>
#include <stdlib.h>
int mystrcmp(char *str1, char *str2)
{
while(*str1 || *str2)
{
if(*str1 == *str2)
{
str1++;
str2++;
}
else
{
return -1;
}
}
if(*str1 == *str2)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
char arr1[] = "hello";
char arr2[] = "hello world";
int ret = mystrcmp(arr1, arr2);
if(ret == 1)
{
printf("这两个字符串相同\n");
}
else
{
printf("这两个字符串不同\n");
}
system("pause");
return 0;
}
3.模拟实现strcat
//模拟实现字符串粘贴函数strcat运行结果:
#include <stdio.h>
#include <stdlib.h>
char* mystrcat(char *str1, char *str2)
{
char *p1 = str1;
char *p2 = str2;
while(*p1)
{
p1++;
}
while(*p2)
{
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0';
return str1;
}
int main()
{
char arr1[100] = "hello ";
char arr2[] = "world";
char *arr = mystrcat(arr1, arr2);
printf("%s\n",arr);
system("pause");
return 0;
}