C++ strcpy、strcat、strcmp和strlen的实现

时间:2022-09-05 22:55:42

针对C++应届生笔试考c++strcpy、strcat、strcmp和strlen的实现,特奉上此文,未雨绸缪,请看代码讲解。

#include <iostream>
#include <assert.h>
#include <windows.h>
using namespace std;

char* strCpy( char* destStr, const char* srcStr ) //字符串拷贝函数
{
 assert( destStr != nullptr && srcStr != nullptr ); //断言,如果条件成立,程序报错
 unsigned int uIndex  = 0;
 while( *( destStr + uIndex ) = *( srcStr + uIndex ) ){ uIndex++; } //字符串拷贝,如果遇'\0',结束拷贝
 return destStr; //返回拷贝后的字符串
}

int strLen( const char* srcStr ) //计算字符串长度函数
{
 assert( srcStr != nullptr ); //断言,如果条件成立,程序报错
 unsigned int uIndex = 0;
 while( *( srcStr + uIndex ) ){ uIndex++; } //遇'\0'结束,uIndex地址索引值即为字符串长度
 return uIndex; //返回长度值
}

void strCat( char* destStr, const char* srcStr ) //字符串链接函数
{
 assert( destStr != nullptr && srcStr != nullptr ); //断言,如果条件成立,程序报错
 unsigned int uIndex = 0;
 while( *( destStr + uIndex ) ){ uIndex++; } //将目标字符串地址索引移至末端
 unsigned int uIndex1 = 0;
 while( *( destStr + uIndex ) = *( srcStr + uIndex1 ) ){ uIndex++; uIndex1++; } //再目标字符串末端开始链接后续字符串
}

int strCmp( const char* destStr, const char* srcStr ) //字符串比较函数
{
 assert( destStr != nullptr && srcStr != nullptr ); //断言,如果条件成立,程序报错
 unsigned uIndex = 0;
 while( *( destStr + uIndex ) == *( srcStr + uIndex ) )
 {
  if( *( destStr + uIndex ) == '\0' && *( srcStr +uIndex ) == '\0' ) //如果条件循环下来到两字符串都成立并结束,返回0
   return 0;
  uIndex++;
 }
 return ( *( destStr + uIndex ) - *( srcStr +uIndex ) ) % 2 ; //如果如果条件循环下来突然不成立,那么假设目标字符串大于源字符串,返回1, 否则返回-1
}

void main()
{
 char szName[ 255 ];
 char szTest[ 9 ] = "MrXo";
 strCat( szTest, "Order" );
 cout << strCpy( szName, szTest )  << endl << strLen( szTest ) << endl;
 char szStr1[] = "check";
 char szStr2[] = "checka";
 cout << strCmp( szStr1, szStr2 ) <<endl;
 system( "pause" );
}