在末尾追加字符的时候进行了判断,加了两个循环,效果不太好,可能略显繁琐,失去性能:
主要需要注意:
1,检查指针有效性;
2,返回目的指针des;
3,源字符串的末尾 '\0' 需要拷贝。
4,如果是在同一块内存中的字符串,则不进行追加拷贝。char *my_strcat_s(char *cDestStr,const char *cSrcStr,int DestLen)
{
assert(cDestStr != NULL &&cSrcStr != NULL);
char *cTmp = cDestStr,*cDst = cDestStr;
int n = 0;
while (cTmp++ != cSrcStr && *cTmp != '\0');//如果两个指针指向同一个字符串内存,返回dest
if (*cTmp != '\0')
{
return NULL;
}
cTmp = cDestStr;
int nDstCount = 0,nSrcCount = 0;
while (*cTmp != '\0')
{
*cTmp++;
nDstCount++;
}
int nUsable = DestLen - nDstCount - 1;
const char *cSrc = cSrcStr;
int nSrc = 0;
while (*cSrc++ != '\0')
{
nSrc++;
}
if (nUsable < nSrc)
{
return NULL;
}
while ((*cTmp++ = *cSrcStr++) != '\0');
*cTmp = '\0';
return cDst;
}