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

来源:互联网 发布:程序员mac 编辑:程序博客网 时间:2024/05/22 14:36

最近在看一些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;}

这里写图片描述