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

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" );
}

 

发布者:admin,转转请注明出处:http://www.yc00.com/news/1689538271a264262.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信