模拟实现strcpy,strncpy函数

strcpy 函数是字符串拷贝函数,他将 src所指字符串拷贝到 dest所指字符串中,包括’\0’

//模拟实现strcpy函数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *my_strcpy(char *dest, const char *src)
{
    assert(dest);
    assert(src);
    char *tmp = dest;
    while (*dest++ = *src++)//'\0'也赋给了dest
    {
        ;
    }
    return tmp;
}
int main()
{
    char a[20];//数组大小要能容纳所给的字符
    char b[] = "abcdef";
    my_strcpy(a, b);
    printf("%s\n",a);
    system("pause");
    return 0;
}

strncpy函数是将src所指字符串的前n个字符拷贝到dest所指字符串中,若需要拷贝的字符个数大于 src所指向字符串的字符个数,将*src中的字符拷贝过去之后,其余部分补上’\0’


//模拟实现strncpy函数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
char *my_strncpy(char *dest, const char *src, int count)
{
    assert(dest);
    assert(src);
    while ((count--)&&(*dest++ = *src++))
    {
        ;
    }
    if (count > 0)
    while (--count)
    {
        *dest++ = '\0';
    }
}
int main()
{
    char a[] = "abcdef";
    char b[] = "ghi";
    my_strncpy(a, b, 5);
    printf("%s\n",a);
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值