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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值