C/C++ 字符串拷贝函数

最近在看一些C++的资料~~看到有讲拷贝函数的写法,觉得听好玩儿的就写了出来,当作记录分享出来。
  • 函数内用临时变量来接受形参,使得原有形参不受函数内部的改变。(不要轻易改掉形参的值)
  • 注意函数内部的指针判空
#include <iostream>
using namespace std;

char *MyStrCpy1(char *strDest, const char *strSrc)
{
    char *tempStrDest = strDest ;//保存首地址
    const char *tempStrSrc = strSrc ;//保存首地址

    if ( tempStrDest == NULL || tempStrSrc == NULL)
    {
        return NULL ;
    }

    if ( tempStrDest == tempStrSrc)
    {
        return tempStrDest ;
    }
    //  一个一个拷贝  最后补充'\0'
    for(; *tempStrSrc!='\0'; ++tempStrDest,++tempStrSrc)
    {
        *tempStrDest = *tempStrSrc;
    }
    *tempStrDest='\0';

    return strDest ;
}

char *MyStrCpy2(char *strDest, const char *strSrc)
{
    char *tempStrDest = strDest ;//保存首地址
    const char *tempStrSrc = strSrc ;//保存首地址

    if ( tempStrDest == NULL || tempStrSrc == NULL)
    {
        return NULL ;
    }

    if ( tempStrDest == tempStrSrc)
    {
        return tempStrDest ;
    }
    //判断是否是‘\0’
    while( (*tempStrDest++ = *tempStrSrc++) !='\0') ;

    return strDest ;
}

char *MyStrCpy3(char *strDest, const char *strSrc)
{
    char *tempStrDest = strDest ;//保存首地址
    const char *tempStrSrc = strSrc ;//保存首地址

    if ( tempStrDest == NULL || tempStrSrc == NULL)
    {
        return NULL ;
    }

    if ( tempStrDest == tempStrSrc)
    {
        return tempStrDest ;
    }
    //直接判断这个条件是否为真
    while( (*tempStrDest++ = *tempStrSrc++)) ;

    return strDest ;
}

int main()
{
    char myString[]="HELLO CSDN ,人间词话·CODE";
    char temp1[100];
    char temp2[100];
    char temp3[100];
    cout<<MyStrCpy1(temp1,myString)<<endl;
    cout<<MyStrCpy2(temp2,myString)<<endl;
    cout<<MyStrCpy3(temp3,myString)<<endl;
}

这里写图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值