1.strcpy
char *my_strcpy(char *dst,char*src)
{
assert(dst!=NULL && src!=NULL);
char *ret = dst; //使用ret保存dst的首地址,最后打印输出只要找到首地址。
while (*src!='\0')
{
*dst = *src;
dst++; src++;
}
*dst = '\0'; //'\0'也需要被拷贝在最后。
return ret;//如果返回的是dst 此时的dst指向的是'\0',传出去的是字符串最后一个元素(即\0)的地址,不会被打印
}
int main()
{
char *str = { "hello world!" };
char str1[20];
printf("%s", my_strcpy(str1, str));
system("pause");
return 0;
}
2.strcat
char *my_strcat(char *dst,const char *src)
{
assert(dst!=NULL && src!=NULL);
int *ret = dst;
while (*dst)//先找到dst所指向字符串的末尾
{
dst++;
}
while (*src)//从dst的末尾开始进行拷贝操作
{
*dst = *src;
dst++;
src++;
}
*dst = '\0'; //最后带上'\0'
return ret;
}
int main()
{
char str[20] = { "hello " };
char *str1 = { "world!" };
printf("str1= %s\n", my_strcat(str, str1));
system("pause");
return 0;
}
3.strcmp
int my_strcmp(const char *str1,const char *str2)
{
int ret = 0;
while (!(ret=((unsigned char*)str1 - (unsigned char*)str2)) && *str1) // 对每个字符进行减操作,并遍历完字符串
{
str1++; str2++;
}
if (ret < 0)
ret = -1;
else if (ret > 0)
ret = 1;
return ret;
}
int main()
{
const char *str1 = "hello!";
const char *str2 = "helo!";
int ret = my_strcmp(str1, str2);
printf("%d\n", ret);
if (ret == 0)
{
printf("字符串相等\n");
}
else
{
printf("字符串不相等\n");
}
system("pause");
return 0;
}
4.strncpy
char *my_strncpy(char *dst,const char *src, int num)
{
char *ret = dst;
assert(dst != NULL&&src != NULL);
while (num--)
{
*dst++ = *src++;
}
*dst = '\0';
return ret;
}
int main()
{
const char *str = "hello world";
char str1[20];
printf("%s\n", my_strncpy(str1, str, 5));
system("pause");
return 0;
}
5.strncat
char *my_strncat(char *dst, char *src, int num)
{
assert(dst != NULL&&src != NULL);
char *ret = dst;
while (*dst)
{
dst++;
}
while (num--)
{
*dst++ = *src++;
}
*dst = '\0';
return ret;
}
int main()
{
char str[20] = { "or not to be" };
char str1[20] = { "to be " };
printf("%s\n", my_strncat(str1, str,strlen(str)));
system("pause");
return 0;
}
6.strncmp
int my_strncmp(const char*str1, const char*str2, int n)
{
assert(str1);
assert(str2);
while (n--)
{
if (*str1 == *str2)
{
str1++;
str2++;
}
else
{
if ((*str1 - *str2)<0)
return -1;
else
return 1;
}
}
return 0;
}
7.strstr
char *my_strstr(const char *str1,const char *str2)
{
assert(str1 != NULL && str2 != NULL);
char*cp = (char *)str1; //cp用来保存str1每次进行比较时所指向的初始位置
char *substr =(char*) str2;
char *s1 = NULL;
if (*str2 == '\0')
return NULL;
while (*cp)
{
s1 = cp;
substr = str2; //每次进入循环substr 又指向str2的初始位置
while (*s1 && *substr && (*s1 == *substr))
{
s1++;
substr++;
}
if (*substr == '\0')
return cp;
cp++;
}
}