C++实现strLen,strCpy,strCmp,strCat

#include "stdafx.h"

int StrLen(const char *pStr)
{
    int nSize = 0;
    if (NULL != pStr)
    {
        char *pStrTemp = (char*)pStr;
        while (*pStrTemp != '\0')
        {
            nSize++;
            pStrTemp++;
        }
    }
    return nSize;
}

bool StrCmp(const char* pStr1, const char*pStr2)
{
    if (NULL != pStr1 && NULL != pStr2)
    {
        if (StrLen((char *)pStr1) == StrLen((char*)pStr2))
        {
            char *pStrTemp1 = (char *)pStr1;
            char *pStrTemp2 = (char *)pStr2;

            while (*pStrTemp1 != '\0')
            {
                if (*pStrTemp1 == *pStrTemp2) {
                    pStrTemp1++;
                    pStrTemp2++;
                }
                else
                {
                    return false;
                }

            }
            return true;
        }
        else
        {
            return false;
        }

    }
    else
    {
        return false;
    }

}

void StrCpy(char *pStrDest, const char *pStrSrc)
{
    if (NULL != pStrDest && NULL != pStrSrc)
    {
        char *pStrSrcTemp = (char*)pStrSrc;
        char *pStrDestTemp = pStrDest;
        while (*pStrDestTemp = *pStrSrcTemp)
        {
            if (*pStrSrcTemp == '\0') {
                break;
            }
            pStrDestTemp++;
            pStrSrcTemp++;
        }
    }
}

char* StrCat(char *pStrDest,const char *pStrSrc)
{
    if (NULL != pStrDest && NULL != pStrSrc)
    {
        char *pStrDestTemp = pStrDest;
        char *pStrSrcTemp = (char*)pStrSrc;

        while (*pStrDestTemp != '\0')
        {
            pStrDestTemp++;
        }

        while (*pStrSrcTemp != '\0')
        {
            *pStrDestTemp = *pStrSrcTemp;
            pStrDestTemp++;
            pStrSrcTemp++;
        }

        ++pStrDestTemp = '\0';

        return pStrDest;
    }
    else
    {
        return NULL;
    }
}

 

测试结果如下:

#include "stdafx.h"

#include "MyStr.h"


int main()
{
cout << "String Size:"<<StrLen("Hello,World")<<endl;

cout << "String Equal?  "<<StrCmp("aaaa", "aaaa")<<endl;

cout << "String Equal?  " << StrCmp("aaaaaa", "aaaa") << endl;

cout << "String Equal?  " << StrCmp("aaaaaa", "bbbb") << endl;

char szName[100] = "";
StrCpy(szName, "I am LiuDehua!");
cout << "String szName:"<<szName << endl;

cout << "合并字符串:" << StrCat(szName, "Everyone loves me!")<<endl;
cout << "Now Name:" << szName<<endl;

return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值