腾讯面试,实现函数
参加腾讯面试,请实现这个函数
char * strcat(const char *strA, const char *strB) 腾讯 面试 strcat
[解决办法]
// 调用者负责释放返回的指针指向的空间
char * Mystrcat(const char *strA, const char *strB)
{
if (strA == NULL
[解决办法]
strB == NULL)
{
return NULL;
}
else
{
int nLenA =strlen(strA);
int nLenB =strlen(strB);
char *str = new char[nLenA+nLenB+1];
memcpy(str ,strA ,nLenA);
memcpy(str + nLenA ,strB,nLenB);
*(str + nLenA + nLenB) = '\0';
return str;
}
}
char* strcat(const char* a, const char* b)
{
int n1 = strlen(a), n2 = strlen(b); // a和b为null是可以计算长度的
int n = n1 + n2;
char* p = new char[n + 1];
if(n1)
memcpy(p, a, n1); // 你自己一个一个复制也可以
if(n2)
memcpy(p + n1, b, n2);
p[n] = '\0';
return p;
}
char * strcat(const char *strA, const char *strB)
{
if (strA == NULL
[解决办法]
strB == NULL) return NULL;
size_t BUF_SIZE = 1024, size = 0;
char* buf = NULL;
while (*strA != '\0'
[解决办法]
*strB != '\0'
[解决办法]
size >= BUF_SIZE)
{
if (!buf && !(buf = (char*)malloc(BUF_SIZE))) return NULL;
if (size >= BUF_SIZE && !(buf = (char*)realloc(buf, BUF_SIZE <<= 1)) && (free(buf), true)) return NULL;
while (*strA != '\0' && size < BUF_SIZE) buf[size++] = *strA++;
while (*strB != '\0' && size < BUF_SIZE) buf[size++] = *strB++;
}
return (buf[size] = '\0', (char*)realloc(buf, size+1));
}