0
点赞
收藏
分享

微信扫一扫

自己实现API strcpy( ,)、strcpy( , , )、strcat( , )

鱼满舱 2022-03-14 阅读 135
c语言
#include <stdio.h>
#include <stdlib.h>

char mystrcpy(char *test1,char *test2)
{
    if(test1==NULL||test2==NULL)
    {
        return NULL;
    }
    
    while( *test2!='\0')//复制也是一个元素一个元素的复制的
    {
     *test1= *test2;   //取出test2中的元素赋值给test1
    //printf("复制给test的是 %s \n",test1);//检验复制过程
    test1++;
    test2++;
    }
    return test1;
}

char mystrncpy(char *test1,char *test2,int n)
{
    if(test1==NULL||test2==NULL)
    {
        return NULL;
    }
    
    while(*test2!='\0'&&n>0)//复制也是一个元素一个元素的复制的
    {
    *test1++=*test2++;
    //printf("复制给test的是 %s \n",test1);//检验复制过程
    //test1++;
    //test2++;
    n--;
    }
    return test1;
}

void mystrcat(char *test1,char *test2)
{
    while(*test1!='\0')
    {
        test1++;
    }
    while(*test2!='\0')
    {
        *test1++=*test2++;
    }
}

int main()
{
    char p1[128]={'\0'};
    char *p="this is a test";
    mystrcpy(p1,p);
    printf("复制给p1的是 %s \n",p1);
    memset(p1,'\0',128);
    mystrncpy(p1,p,6);
    printf("指定个数的复制给p1的是 %s \n",p1);
    
    char a[128]="hello";//被拼接的还必须是数组这种
    char *b=" word";
    //puts(a);
    mystrcat(a,b);
    puts(a);
    
    system("pause");
    return 0;
}
举报

相关推荐

0 条评论