#include <iostream>
#include <assert.h>
//strcpy标准实现
char* CustomStrCpy1( char* Dest, const char* Src )
{
if( nullptr == Dest || nullptr == Src )
{
assert( false );
return nullptr;
}
char* p = Dest;
while( *p++=*Src++ );
return Dest;
}
//strcpy内存实现
char* CustomStrCpy2( char* Dest, const char* Src )
{
if( nullptr == Dest || nullptr == Src )
{
assert( false );
return nullptr;
}
memcpy( Dest, Src, strlen( Src ) + 1 );
return Dest;
}
//strcpy数组实现
char* CustomStrCpy3( char* Dest, const char* Src )
{
if( nullptr == Dest || nullptr == Src )
{
assert( false );
return nullptr;
}
const size_t SrcLen = strlen( Src );
for( size_t i = 0; i <= SrcLen; ++i )
{
Dest[ i ] = Src[ i ];
}
return Dest;
}
//strcpy递归
char* CustomStrCpy4( char* Dest, const char* Src, int DestOffset = 0 )
{
if( nullptr == Dest || nullptr == Src )
{
assert( false );
return nullptr;
}
*Dest = *Src;
if( '\0' == *Src )
{
return Dest - DestOffset;
}
return CustomStrCpy4( Dest + 1, Src + 1, DestOffset + 1 );
}
int main()
{
//测试
char Test[ 32 ];
std::cout<<CustomStrCpy1( Test, "123" )<<std::endl;
std::cout<<CustomStrCpy2( Test, "456" )<<std::endl;
std::cout<<CustomStrCpy3( Test, "789" )<<std::endl;
std::cout<<CustomStrCpy4( Test, "123" )<<std::endl;
//效率的话大家可以尝试自己修改代码比对一下
//不过我觉得应该是内存思想方式效率最高
//其他函数如strcat的实现也都差不多
return 0;
}
字符串拷贝函数strcpy的几种实现思想方式
最新推荐文章于 2024-09-06 00:06:01 发布